2020-12-05 07:17:45 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Util\Media;
|
|
|
|
|
|
|
|
use App\Util\Blurhash\Blurhash as BlurhashEngine;
|
|
|
|
use App\Media;
|
|
|
|
|
|
|
|
class Blurhash {
|
|
|
|
|
2021-01-31 00:28:35 +00:00
|
|
|
const DEFAULT_HASH = 'U4Rfzst8?bt7ogayj[j[~pfQ9Goe%Mj[WBay';
|
|
|
|
|
2020-12-05 07:17:45 +00:00
|
|
|
public static function generate(Media $media)
|
|
|
|
{
|
2021-01-31 00:28:35 +00:00
|
|
|
if(!in_array($media->mime, ['image/png', 'image/jpeg', 'video/mp4'])) {
|
|
|
|
return self::DEFAULT_HASH;
|
|
|
|
}
|
|
|
|
|
|
|
|
if($media->thumbnail_path == null) {
|
|
|
|
return self::DEFAULT_HASH;
|
2020-12-05 07:17:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
$file = storage_path('app/' . $media->thumbnail_path);
|
|
|
|
|
|
|
|
if(!is_file($file)) {
|
2021-01-31 00:28:35 +00:00
|
|
|
return self::DEFAULT_HASH;
|
2020-12-05 07:17:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
$image = imagecreatefromstring(file_get_contents($file));
|
2021-01-31 00:28:35 +00:00
|
|
|
if(!$image) {
|
|
|
|
return self::DEFAULT_HASH;
|
|
|
|
}
|
2020-12-05 07:17:45 +00:00
|
|
|
$width = imagesx($image);
|
|
|
|
$height = imagesy($image);
|
|
|
|
|
|
|
|
$pixels = [];
|
|
|
|
for ($y = 0; $y < $height; ++$y) {
|
|
|
|
$row = [];
|
|
|
|
for ($x = 0; $x < $width; ++$x) {
|
|
|
|
$index = imagecolorat($image, $x, $y);
|
|
|
|
$colors = imagecolorsforindex($image, $index);
|
|
|
|
|
|
|
|
$row[] = [$colors['red'], $colors['green'], $colors['blue']];
|
|
|
|
}
|
|
|
|
$pixels[] = $row;
|
|
|
|
}
|
|
|
|
|
|
|
|
$components_x = 4;
|
|
|
|
$components_y = 4;
|
|
|
|
$blurhash = BlurhashEngine::encode($pixels, $components_x, $components_y);
|
|
|
|
if(strlen($blurhash) > 191) {
|
2021-01-31 00:28:35 +00:00
|
|
|
return self::DEFAULT_HASH;
|
2020-12-05 07:17:45 +00:00
|
|
|
}
|
|
|
|
return $blurhash;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|