blurhash/TypeScript
2019-08-06 08:58:19 +03:00
..
demo Make typescript demo page prettier 2018-06-04 18:12:42 +03:00
src TS: improve validation, export isBlurhashValid function 2019-06-29 13:59:02 +03:00
.gitignore remove TS dist from git 2019-06-24 13:46:47 +03:00
.npmignore Beginning of documentation! 2018-05-31 13:42:11 +03:00
.prettierrc add and configure prettier 2019-06-24 14:00:00 +03:00
CHANGELOG.md TS: version bump 2019-06-29 14:00:04 +03:00
package.json TS: dependency updates 2019-07-31 15:14:48 +03:00
README.md TS fix: add missing arguments to decode in readme 2019-08-06 08:58:19 +03:00
tsconfig.json Fix tsconfig so demo works again 2019-06-27 14:26:45 +03:00
webpack.config.js Beginning of documentation! 2018-05-31 13:42:11 +03:00
yarn.lock TS: dependency updates 2019-07-31 15:14:48 +03:00

blurhash

NPM Version NPM Downloads

JavaScript encoder and decoder for the Wolt BlurHash algorithm

Install

npm install --save blurhash

See react-blurhash to use blurhash with React.

API

decode(blurhash: string, width: number, height: number, punch?: number) => Uint8ClampedArray

Decodes a blurhash string to pixels

Example

import { decode } from "blurhash";

const pixels = decode("LEHV6nWB2yk8pyo0adR*.7kCMdnj", 32, 32);

const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const imageData = ctx.createImageData(width, height);
imageData.data.set(pixels);
ctx.putImageData(imageData, 0, 0);
document.body.append(canvas);

encode(pixels: Uint8ClampedArray, width: number, height: number, componentX: number, componentY: number) => string

Encodes pixels to a blurhash string

import { encode } from "blurhash";

const loadImage = async src =>
  new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve(img);
    img.onerror = (...args) => reject(args);
    img.src = src;
  });

const getImageData = image => {
  const canvas = document.createElement("canvas");
  canvas.width = image.width;
  canvas.height = image.height;
  const context = canvas.getContext("2d");
  context.drawImage(image, 0, 0);
  return context.getImageData(0, 0, image.width, image.height);
};

const encodeImageToBlurhash = async imageUrl => {
  const image = await loadImage(imageUrl);
  const imageData = getImageData(image);
  return encode(imageData.data, imageData.width, imageData.height, 4, 4);
};

isBlurhashValid(blurhash: string) => { result: boolean; errorReason?: string }

import { isBlurhashValid } from "blurhash";

const validRes = isBlurhashValid("LEHV6nWB2yk8pyo0adR*.7kCMdnj");
// { result: true }

const invalidRes = isBlurhashValid("???");
// { result: false, errorReason: "The blurhash string must be at least 6 characters" }