Blurhash Python Library

1.1.5 · active · verified Thu Apr 16

The `blurhash` library is a pure-Python implementation of the BlurHash algorithm, allowing you to create compact, unique hashes for images that represent a blurred placeholder. This is useful for lazy-loading images on the web. The current version is 1.1.5, with releases occurring infrequently, primarily for distribution updates rather than core code changes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to encode an image into a BlurHash string and then decode that string back into a blurred image. It uses Pillow for image creation and manipulation, showing how to prepare pixel data for the `blurhash` library's `encode` function, which expects a flat list of RGBA values.

import os
from PIL import Image
from blurhash import encode, decode

# 1. Create a dummy image for demonstration
width, height = 32, 32
img = Image.new('RGBA', (width, height), color = 'red')
img.putpixel((0, 0), (0, 255, 0, 255)) # Green pixel at top-left
img.putpixel((width-1, height-1), (0, 0, 255, 255)) # Blue pixel at bottom-right

# Prepare image data for blurhash (flat list of RGBA values)
# The library expects pixel data as a flat list, not a Pillow Image object directly.
# If your image is RGB, you might need to convert it to RGBA first.
pixel_data = []
for y in range(height):
    for x in range(width):
        r, g, b, a = img.getpixel((x, y))
        pixel_data.extend([r, g, b, a])

# 2. Encode the image
x_components = 4 # How many color components horizontally
y_components = 3 # How many color components vertically
blurhash_string = encode(pixel_data, width, height, x_components, y_components)
print(f"Generated BlurHash: {blurhash_string}")

# 3. Decode the blurhash string back into pixel data
output_width = 160
output_height = 90

decoded_pixels = decode(blurhash_string, output_width, output_height)

# 4. Reconstruct image from decoded pixels (using Pillow)
decoded_img = Image.new('RGBA', (output_width, output_height))
decoded_img.putdata(list(zip(*[iter(decoded_pixels)]*4)))

# 5. Save the original and decoded images
original_path = 'original_image.png'
decoded_path = 'decoded_blurhash.png'
img.save(original_path)
decoded_img.save(decoded_path)
print(f"Original image saved to {original_path}")
print(f"Decoded blurhash image saved to {decoded_path}")

# Clean up (optional)
# os.remove(original_path)
# os.remove(decoded_path)

view raw JSON →