Blurhash.php 1.6 KB

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