PHP code example of kornrunner / blurhash
1. Go to this page and download the library: Download kornrunner/blurhash library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
kornrunner / blurhash example snippets
ornrunner\Blurhash\Blurhash;
$file = 'test/data/img1.jpg';
$image = imagecreatefromstring(file_get_contents($file));
$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 = 3;
$blurhash = Blurhash::encode($pixels, $components_x, $components_y);
// LEHV9uae2yk8pyo0adR*.7kCMdnj
use kornrunner\Blurhash\Blurhash;
use Intervention\Image\Colors\Rgb\Channels\Blue;
use Intervention\Image\Colors\Rgb\Channels\Green;
use Intervention\Image\Colors\Rgb\Channels\Red;
use Intervention\Image\Colors\Rgb\Color as RgbColor;
use Intervention\Image\Colors\Rgb\Colorspace as RgbColorspace;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\ImageManager;
$file = 'test/data/img1.jpg';
$manager = new ImageManager(new Driver());
$image = $manager->read($file);
$width = $image->width();
$height = $image->height();
$pixels = [];
for ($y = 0; $y < $height; ++$y) {
$row = [];
for ($x = 0; $x < $width; ++$x) {
$colors = $image->pickColor($x, $y);
if (!($colors instanceof RgbColor)) {
$colors = $colors->convertTo(new RgbColorspace());
}
$row[] = [
$colors->channel(Red::class)->value(),
$colors->channel(Green::class)->value(),
$colors->channel(Blue::class)->value(),
];
}
$pixels[] = $row;
}
$components_x = 4;
$components_y = 3;
$blurhash = Blurhash::encode($pixels, $components_x, $components_y);
// LEHV9uae2yk8pyo0adR*.7kCMdnj
ornrunner\Blurhash\Blurhash;
$blurhash = 'LEHV6nWB2yk8pyo0adR*.7kCMdnj';
$width = 269;
$height = 173;
$pixels = Blurhash::decode($blurhash, $width, $height);
$image = imagecreatetruecolor($width, $height);
for ($y = 0; $y < $height; ++$y) {
for ($x = 0; $x < $width; ++$x) {
[$r, $g, $b] = $pixels[$y][$x];
imagesetpixel($image, $x, $y, imagecolorallocate($image, $r, $g, $b));
}
}
imagepng($image, 'blurhash.png');