What is blurhash?
The blurhash npm package is a tool for generating and decoding BlurHash strings. BlurHash is a compact representation of a placeholder for an image, which can be used to display a blurred preview while the full image is loading.
What are blurhash's main functionalities?
Encoding an image to a BlurHash string
This feature allows you to encode an image into a BlurHash string. The `encode` function takes the image data, width, height, and the number of components for the x and y axes as parameters.
const { encode } = require('blurhash');
const imageData = new Uint8ClampedArray([/* image data */]);
const width = 32; // width of the image
const height = 32; // height of the image
const blurHash = encode(imageData, width, height, 4, 4);
console.log(blurHash);
Decoding a BlurHash string to an image
This feature allows you to decode a BlurHash string back into an image. The `decode` function takes the BlurHash string, width, height, and an optional punch parameter to control the contrast of the output image.
const { decode } = require('blurhash');
const blurHash = 'LEHV6nWB2yk8pyo0adR*.7kCMdnj';
const width = 32; // width of the resulting image
const height = 32; // height of the resulting image
const punch = 1; // controls the contrast of the output image
const imageData = decode(blurHash, width, height, punch);
console.log(imageData);
Rendering a BlurHash string to a canvas
This feature allows you to render a decoded BlurHash string to an HTML canvas element. The code demonstrates decoding a BlurHash string and then drawing the resulting image data onto a canvas.
const { decode } = require('blurhash');
const blurHash = 'LEHV6nWB2yk8pyo0adR*.7kCMdnj';
const width = 32;
const height = 32;
const punch = 1;
const imageData = decode(blurHash, width, height, punch);
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
const imageDataObject = new ImageData(imageData, width, height);
ctx.putImageData(imageDataObject, 0, 0);
document.body.appendChild(canvas);
Other packages similar to blurhash
lqip-modern
The lqip-modern package generates low-quality image placeholders (LQIP) for images. It provides a similar functionality to BlurHash by creating a blurred, low-resolution version of an image to be used as a placeholder while the full image loads. Unlike BlurHash, which uses a compact string representation, lqip-modern generates actual image data.
sqip
The sqip package (SVG-based LQIP) generates SVG placeholders for images. It creates a simplified, abstract representation of an image using SVG, which can be used as a placeholder. This approach is different from BlurHash, which uses a string-based representation and focuses on blurring the image.