Novis\Image\Image::placeholder
Novis\Image\Image::placeholder(
Core\Bytes::Source $data,
PlaceholderKind $kind,
): stringReturns a short text that a web page can draw as a blurred preview of an image.
Image::placeholder reads an encoded image and returns a string of about 30 characters. You can pass bytes, an open Core\IO\File or an uploaded Core\Request\Part. You send this string with the page. A small script in the browser draws it as a blurred picture while the real image loads. The average colour of the preview is the average colour of the image.
The Image::PlaceholderKind you pass sets the format of the text: BlurHash or ThumbHash. Use the one your front-end script reads. Bytes that are not an image throw a ParseError.
Good to know: make the placeholder once, when the image is uploaded, and save it with the image. The text is short, so it fits in a database column or a JSON response.
The examples below show a placeholder in a JSON response, a placeholder for every product photo, and the error for bytes that are not an image.
Parameters
$dataCore\Bytes::Source$kindPlaceholderKind
Return value
Returns string.
Examples
Send it with the page
<?nvs// Shows how a shop sends a placeholder with each product, so the page shows a preview at once.use Novis\Image\Color;use Novis\Image\Image;
// A green product photo of 120 by 80 pixels, encoded as PNG.tainted bytes $photo = Image::create(120, 80, Color::hex('#16a34a'))->encode();
// The page gets the image address and its placeholder together.string $placeholder = Image::placeholder($photo, Image::PlaceholderKind::BlurHash);echo Core\Json::encode({ image: '/images/product-7.png', placeholder: $placeholder }), "\n";{"image":"/images/product-7.png","placeholder":"L12nTqlPfQlPl%fjfQfjfQfQfQfQ"}One for every photo
<?nvs// Shows how a shop makes a placeholder for every product photo when it saves them.use Novis\Image\Color;use Novis\Image\Image;
// Three product photos, one in each colour.array<string> $colours = ['#dc2626', '#16a34a', '#2563eb'];
// Each photo gets its own text. Save it next to the photo.foreach ($colours as string $colour) { tainted bytes $photo = Image::create(80, 80, Color::hex($colour))->encode(); echo $colour, ': ', Image::placeholder($photo, Image::PlaceholderKind::ThumbHash), "\n";}#dc2626: 2GoDBwB4eHh4iId3iHiHiIh4cJBoCIgG#16a34a: legABwB4b3mKeHd3eIeHd3eHiEBYd5MA#2563eb: 34IBBwAHCy+Jd3iKeIeIl4d3iagGkIgIText is not an image
<?nvs// Shows the error `Image::placeholder` throws for bytes that are not an image.use Novis\Image\Image;
bytes $upload = '<html>not a picture</html>' as bytes;
// The bytes are not an image, so this throws a `ParseError`.try { echo Image::placeholder($upload, Image::PlaceholderKind::BlurHash), "\n";} catch (ParseError $e) { echo "ParseError: the upload is not an image\n";}ParseError: the upload is not an image