Blurhash.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace App\Util\Media;
  3. use App\Util\Blurhash\Blurhash as BlurhashEngine;
  4. use App\Media;
  5. class Blurhash {
  6. const DEFAULT_HASH = 'U4Rfzst8?bt7ogayj[j[~pfQ9Goe%Mj[WBay';
  7. public static function generate(Media $media)
  8. {
  9. if(!in_array($media->mime, ['image/png', 'image/jpeg', 'video/mp4'])) {
  10. return self::DEFAULT_HASH;
  11. }
  12. if($media->thumbnail_path == null) {
  13. return self::DEFAULT_HASH;
  14. }
  15. $file = storage_path('app/' . $media->thumbnail_path);
  16. if(!is_file($file)) {
  17. return self::DEFAULT_HASH;
  18. }
  19. $image = imagecreatefromstring(file_get_contents($file));
  20. if(!$image) {
  21. return self::DEFAULT_HASH;
  22. }
  23. $width = imagesx($image);
  24. $height = imagesy($image);
  25. $pixels = [];
  26. for ($y = 0; $y < $height; ++$y) {
  27. $row = [];
  28. for ($x = 0; $x < $width; ++$x) {
  29. $index = imagecolorat($image, $x, $y);
  30. $colors = imagecolorsforindex($image, $index);
  31. $row[] = [$colors['red'], $colors['green'], $colors['blue']];
  32. }
  33. $pixels[] = $row;
  34. }
  35. // Free the allocated GdImage object from memory:
  36. imagedestroy($image);
  37. $components_x = 4;
  38. $components_y = 4;
  39. $blurhash = BlurhashEngine::encode($pixels, $components_x, $components_y);
  40. if(strlen($blurhash) > 191) {
  41. return self::DEFAULT_HASH;
  42. }
  43. return $blurhash;
  44. }
  45. }