Blurhash.php 949 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. namespace App\Util\Media;
  3. use App\Util\Blurhash\Blurhash as BlurhashEngine;
  4. use App\Media;
  5. class Blurhash {
  6. public static function generate(Media $media)
  7. {
  8. if(!in_array($media->mime, ['image/png', 'image/jpeg'])) {
  9. return;
  10. }
  11. $file = storage_path('app/' . $media->thumbnail_path);
  12. if(!is_file($file)) {
  13. return;
  14. }
  15. $image = imagecreatefromstring(file_get_contents($file));
  16. $width = imagesx($image);
  17. $height = imagesy($image);
  18. $pixels = [];
  19. for ($y = 0; $y < $height; ++$y) {
  20. $row = [];
  21. for ($x = 0; $x < $width; ++$x) {
  22. $index = imagecolorat($image, $x, $y);
  23. $colors = imagecolorsforindex($image, $index);
  24. $row[] = [$colors['red'], $colors['green'], $colors['blue']];
  25. }
  26. $pixels[] = $row;
  27. }
  28. $components_x = 4;
  29. $components_y = 4;
  30. $blurhash = BlurhashEngine::encode($pixels, $components_x, $components_y);
  31. if(strlen($blurhash) > 191) {
  32. return;
  33. }
  34. return $blurhash;
  35. }
  36. }