Convert Figma logo to code with AI

woltapp logoblurhash

A very compact representation of a placeholder for an image.

15,631
353
15,631
43

Top Related Projects

Grab the color palette from an image using just Javascript. Works in the browser and in Node.

28,864

High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, AVIF and TIFF images. Uses the libvips library.

Quick Overview

BlurHash is a compact representation of a placeholder for an image. It encodes an image into a short string that can be easily stored and used to create a blurred preview of the full image. This technique is particularly useful for improving perceived loading times in applications and websites.

Pros

  • Extremely small payload size, typically 20-30 characters
  • Fast encoding and decoding process
  • Provides a visually pleasing placeholder for images
  • Supports multiple programming languages and platforms

Cons

  • Limited color accuracy compared to the original image
  • May not be suitable for images with fine details or text
  • Requires additional processing on both server and client sides
  • Not a replacement for proper image optimization techniques

Code Examples

Encoding an image to BlurHash:

import BlurHashKit

let image = UIImage(named: "example.jpg")!
let blurHash = BlurHash(from: image, componentX: 4, componentY: 3)
let encodedString = blurHash.string

Decoding a BlurHash to an image:

import BlurHashKit

let encodedString = "LGF5]+Yk^6#M@-5c,1J5@[or[Q6."
let blurHash = BlurHash(string: encodedString)!
let image = blurHash.image(size: CGSize(width: 32, height: 32))

Using BlurHash in a SwiftUI view:

import SwiftUI
import BlurHashKit

struct BlurHashImage: View {
    let blurHash: String
    let size: CGSize
    
    var body: some View {
        if let blurHash = BlurHash(string: blurHash),
           let image = blurHash.image(size: size) {
            Image(uiImage: image)
                .resizable()
                .aspectRatio(contentMode: .fit)
        } else {
            Color.gray
        }
    }
}

Getting Started

To use BlurHash in your Swift project:

  1. Add the BlurHash package to your project:

    dependencies: [
        .package(url: "https://github.com/woltapp/blurhash-swift.git", from: "1.0.0")
    ]
    
  2. Import the library in your Swift file:

    import BlurHashKit
    
  3. Encode an image:

    let image = UIImage(named: "example.jpg")!
    let blurHash = BlurHash(from: image, componentX: 4, componentY: 3)
    let encodedString = blurHash.string
    
  4. Decode a BlurHash string:

    let blurHash = BlurHash(string: encodedString)!
    let image = blurHash.image(size: CGSize(width: 32, height: 32))
    

Competitor Comparisons

Pros of react-resizable-panels

  • Specifically designed for React applications, offering seamless integration
  • Provides a flexible layout system with resizable panels
  • Supports both horizontal and vertical panel arrangements

Cons of react-resizable-panels

  • Limited to layout functionality, doesn't address image placeholders or compression
  • May require additional setup and configuration for complex layouts
  • Potentially higher performance overhead for large, complex panel structures

Code Comparison

react-resizable-panels:

import { PanelGroup, Panel, PanelResizeHandle } from "react-resizable-panels";

<PanelGroup direction="horizontal">
  <Panel>Left panel</Panel>
  <PanelResizeHandle />
  <Panel>Right panel</Panel>
</PanelGroup>

blurhash:

import { encode, decode } from "blurhash";

const blurhash = encode(pixels, width, height, 4, 4);
const pixels = decode(blurhash, width, height);

Summary

While react-resizable-panels focuses on creating flexible, resizable layouts for React applications, blurhash specializes in generating compact representations of images for placeholders. react-resizable-panels offers more layout control but is limited to React, while blurhash provides a solution for image placeholders across various platforms. The choice between the two depends on the specific needs of the project, whether it's layout management or image optimization.

Grab the color palette from an image using just Javascript. Works in the browser and in Node.

Pros of Color Thief

  • Extracts dominant colors and color palettes from images
  • Lightweight and easy to use with minimal setup
  • Works well for generating color schemes based on image content

Cons of Color Thief

  • Limited to color extraction, doesn't provide image compression or placeholder generation
  • May not perform as well with complex or highly detailed images
  • Requires the full image to be loaded before processing

Code Comparison

Color Thief:

const colorThief = new ColorThief();
const dominantColor = colorThief.getColor(imageElement);
const palette = colorThief.getPalette(imageElement, 5);

Blurhash:

const blurhash = Blurhash.encode(imageData, width, height, 4, 3);
const pixels = Blurhash.decode(blurhash, width, height);

Key Differences

  • Purpose: Color Thief focuses on color extraction, while Blurhash generates compact representations of images for placeholders
  • Output: Color Thief provides color values, Blurhash produces a string hash that can be decoded into a blurred image
  • Use cases: Color Thief is ideal for theming and color-based design, Blurhash excels in creating loading placeholders and thumbnails

Both libraries serve different purposes and can be complementary in certain scenarios. Color Thief is better suited for color-based analysis and design tasks, while Blurhash offers a solution for efficient image placeholders and previews.

28,864

High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, AVIF and TIFF images. Uses the libvips library.

Pros of Sharp

  • Comprehensive image processing library with extensive features
  • High performance due to use of libvips image processing library
  • Supports a wide range of input and output formats

Cons of Sharp

  • Larger package size and more dependencies
  • Steeper learning curve due to more complex API
  • May be overkill for simple image processing tasks

Code Comparison

Sharp:

sharp(inputBuffer)
  .resize(200, 200)
  .toFormat('webp')
  .toBuffer((err, buffer) => {
    // Handle resized image buffer
  });

BlurHash:

const blurhash = encode(pixels, width, height, 4, 4);
// Use blurhash string for placeholder

Summary

Sharp is a powerful and versatile image processing library, offering a wide range of features and high performance. It's ideal for complex image manipulation tasks but may be excessive for simpler use cases. BlurHash, on the other hand, focuses specifically on generating compact representations of images for use as placeholders. It's simpler to use and has a smaller footprint, making it a good choice for projects that primarily need placeholder generation functionality.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

BlurHash

BlurHash is a compact representation of a placeholder for an image.

Why would you want this?

Does your designer cry every time you load their beautifully designed screen, and it is full of empty boxes because all the images have not loaded yet? Does your database engineer cry when you want to solve this by trying to cram little thumbnail images into your data to show as placeholders?

BlurHash will solve your problems! How? Like this:

You can also see nice examples and try it out yourself at blurha.sh!

How does it work?

In short, BlurHash takes an image, and gives you a short string (only 20-30 characters!) that represents the placeholder for this image. You do this on the backend of your service, and store the string along with the image. When you send data to your client, you send both the URL to the image, and the BlurHash string. Your client then takes the string, and decodes it into an image that it shows while the real image is loading over the network. The string is short enough that it comfortably fits into whatever data format you use. For instance, it can easily be added as a field in a JSON object.

In summary:

   

Want to know all the gory technical details? Read the algorithm description.

Implementing the algorithm is actually quite easy! Implementations are short and easily ported to your favourite language or platform.

Implementations

So far, we have created these implementations:

  • C - An encoder implementation in portable C code.
  • Swift - Encoder and decoder implementations, and a larger library offering advanced features. There is also an example app to play around with the algorithm.
  • Kotlin - A decoder implementation for Android.
  • TypeScript - Encoder and decoder implementations, and an example page to test.
  • Python - Integration of the C encoder code into Python.

These cover our use cases, but could probably use polishing, extending and improving. There are also these third party implementations that we know of:

  • Pure Python - Implementation of both the encoder and decoder in pure Python.
  • One version in Go, and another version in Go.
  • PHP - Encoder and decoder implementations in pure PHP.
  • Java - Encoder implementation in Java.
  • Clojure - Encoder and decoder implementations in Clojure.
  • Nim - Encoder and decoder implementation in pure Nim.
  • Rust and WebAssembly - Encoder and decoder implementations in Rust. Distributed as both native Rust and WebAssembly packages.
  • Ruby - Encoder implementation in Ruby.
  • Crystal - Encoder implementation in pure Crystal.
  • Elm - Encoder and decoder in Elm.
  • Dart - Encoder and decoder implementation in C into Dart using dart-ffi.
  • Pure Dart - Encoder and decoder implementation in pure Dart.
  • .NET - Encoder and decoder in C#.
  • JavaScript - Encoder and decoder implementation in pure JavaScript.
  • .NET - Encoder implementation in C#.
  • Haskell - Encoder and decoder in pure Haskell.
  • Scala - Encoder and decoder in Scala.
  • Elixir - Encoder implementation in pure Elixir.
  • ReScript - Encoder and decoder implementation in ReScript (BuckleScript).
  • JavaScript - Tiny optimized decoder implementation JS.
  • Xojo - Encoder and decoder implementation in pure Xojo.
  • React Native - UI Component for React Native. (Decoder in Swift and Kotlin)
  • Zig - Encoder implementation in Zig.
  • Titanium SDK - Decoder for Titanium SDK (Android)
  • BQN - Encoder, decoder and terminal viewer in pure BQN.
  • Jetpack Compose - Decoder Jetpack Compose implementation
  • C++ - Encoder and decoder in C++.
  • Kotlin Multiplatform - Encoding & decoding for Android, iOS & JVM
  • OCaml - Encoder implementation in OCaml.

Can't find the language you're looking for? Try your luck with the GitHub search. For example, here are the search results for repos which have "blurhash" in their name.

Perhaps you'd like to help extend this list? Which brings us to...

Contributing

We'd love contributions! The algorithm is very simple - less than two hundred lines of code - and can easily be ported to your platform of choice. And having support for more platforms would be wonderful! So, Java decoder? Golang encoder? Haskell? Rust? We want them all!

We will also try to tag any issues on our issue tracker that we'd love help with, so if you just want to dip in, go have a look.

You can file a pull request with us, or you can start your own repo and project if you want to run everything yourself, we don't mind.

If you do want to contribute to this project, we have a code of conduct.

Users

Who uses BlurHash? Here are some projects we know about:

  • Wolt - We are of course using it ourselves. BlurHashes are used in the mobile clients on iOS and Android, as well as on the web, as placeholders during image loading.
  • Mastodon - The Mastodon decentralised social media network uses BlurHashes both as loading placeholders, as well as for hiding media marked as sensitive.
  • Signal - Signal Private Messenger uses Blurhashes as placeholders before photo & video messages are downloaded in chat conversations.
  • Jellyfin - Jellyfin the free software media system uses Blurhashes as placeholders for images of movies and TV shows when they are being downloaded.

Good Questions

How fast is encoding? Decoding?

These implementations are not very optimised. Running them on very large images can be a bit slow. The performance of the encoder and decoder are about the same for the same input or output size, so decoding very large placeholders, especially on your UI thread, can also be a bit slow.

However! The trick to using the algorithm efficiently is to not run it on full-sized data. The fine detail of an image is all thrown away, so you should scale your images down before running BlurHash on them. If you are creating thumbnails, run BlurHash on those instead of the full images.

Similarly, when displaying the placeholders, very small images work very well when scaled up. We usually decode placeholders that are 32 or even 20 pixels wide, and then let the UI layer scale them up, which is indistinguishable from decoding them at full size.

How do I pick the number of X and Y components?

It depends a bit on taste. The more components you pick, the more information is retained in the placeholder, but the longer the BlurHash string will be. Also, it doesn't always look good with too many components. We usually go with 4 by 3, which seems to strike a nice balance.

However, you should adjust the number of components depending on the aspect ratio of your images. For instance, very wide images should have more X components and fewer Y components.

The Swift example project contains a test app where you can play around with the parameters and see the results.

What is the punch parameter in some of these implementations?

It is a parameter that adjusts the contrast on the decoded image. 1 means normal, smaller values will make the effect more subtle, and larger values will make it stronger. This is basically a design parameter, which lets you adjust the look.

Technically, what it does is scale the AC components up or down.

Is this only useful as an image loading placeholder?

Well, that is what it was designed for originally, but it turns out to be useful for a few other things:

  • Masking images without having to use expensive blurs - Mastodon uses it for this.
  • The data representation makes it quite easy to extract colour averages of the image for different areas. You can easily find approximations of things like the average colour of the top edge of the image, or of a corner. There is some code in the Swift BlurHashKit implementation to experiment with this. Also, the average colour of the entire image is just the DC component and can be decoded even without implementing any of the more complicated DCT stuff.
  • We have been meaning to try to implement tinted drop shadows for UI elements by using the BlurHash and extending the borders. Haven't actually had time to implement this yet though.

Why base 83?

First, 83 seems to be about how many low-ASCII characters you can find that are safe for use in all of JSON, HTML and shells.

Secondly, 83 * 83 is very close to, and a little more than, 19 * 19 * 19, making it ideal for encoding three AC components in two characters.

What about using the full Unicode character set to get a more efficient encoding?

We haven't looked into how much overhead UTF-8 encoding would introduce versus base 83 in single-byte characters, but the encoding and decoding would probably be a lot more complicated, so in the spirit of minimalism BlurHash uses the simpler option. It might also be awkward to copy-paste, depending on OS capabilities.

If you think it can be done and is worth it, though, do make your own version and show us! We'd love to see it in action.

What about other basis representations than DCT?

This is something we'd love to try. The DCT looks quite ugly when you increase the number of components, probably because the shape of the basis functions becomes too visible. Using a different basis with more aesthetically pleasing shape might be a big win.

However, we have not managed come up with one. Some experimenting with a Fourier-Bessel base, targeted at images that are going to be cropped into circles has been done, but without much success. Here again we'd love to see what you can come up with!

Authors

NPM DownloadsLast 30 Days