All Projects → kornrunner → Php Blurhash

kornrunner / Php Blurhash

Licence: mit
Pure PHP implementation of Blurhash (https://github.com/woltapp/blurhash)

php-blurhash Build Status Build status Coverage Status Latest Stable Version

A pure PHP implementation of Blurhash. The API is stable, however the hashing function in either direction may not be.

Blurhash is an algorithm written by Dag Ågren for Wolt (woltapp/blurhash) that encodes an image into a short (~20-30 byte) ASCII string. When you decode the string back into an image, you get a gradient of colors that represent the original image. This can be useful for scenarios where you want an image placeholder before loading, or even to censor the contents of an image a la Mastodon.

Installation

$ composer require kornrunner/blurhash

Usage

Encoding an image to blurhash expects two-dimensional array of colors of image pixels, sample code:

<?php

require_once 'vendor/autoload.php';

use kornrunner\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

For decoding of blurhash people will likely go for some other implementation (JavaScript/TypeScript). PHP decoder returns a pixel array that can be used to generate the image:

<?php

require_once 'vendor/autoload.php';

use kornrunner\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');

Contributing

Issues, feature requests or improvements welcome!

Licence

This project is licensed under the MIT License.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].