blurhash README

The project's README from github.com/woltapp/blurhash. As one markdown file: README.md.

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:

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

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:

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:

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

blurhash (woltapp/blurhash)

Searching Database…

17.1K ·GitHub
Что это такое?BlurHash — это компактная заглушка для изображения: строка из 20–30 символов, в которую закодировано размытое превью картинки. Клиент декодирует её и показывает, пока настоящее изображение загружается.
Это приложение, которое я устанавливаю, или библиотека?Это алгоритм, который используется через небольшие библиотеки — вся реализация занимает меньше 200 строк кода, поэтому её легко портировать на любой язык или платформу.
С чего начать?Добавьте реализацию для своего языка, закодируйте каждое изображение один раз на бэкенде и передавайте строку из 20–30 символов внутри того формата данных, который вы уже отправляете клиентам.
Он поддерживает мой язык или стек?Официальные реализации есть для C (кодировщик), Swift, Kotlin (декодер для Android), TypeScript и Python; сторонние порты добавляют Go, PHP, Java, Rust, Ruby, Elixir, Dart, .NET и другие.
Есть ли у кодирования и декодирования проблемы с производительностью?Да: реализации не оптимизированы и сильно замедляются на очень больших изображениях. Кодируйте уменьшенные версии картинок и декодируйте заглушки шириной около 20–32 пикселей, а масштабирование доверяйте интерфейсу.
Он нужен мне на бэкенде, на клиенте или там и там?И там и там: бэкенд кодирует и хранит строку вместе с каждым изображением, а клиент декодирует её в заглушку, которая показывается, пока настоящее изображение загружается по сети.
Он работает на мобильных и в вебе?Да — официальные реализации сделаны для iOS (Swift), Android (Kotlin) и веба (TypeScript), а сама Wolt использует BlurHash во всех своих клиентах: iOS, Android и веб.
Как выбрать количество компонент X и Y?Это дело вкуса: больше компонент — больше деталей, но строка становится длиннее и результат может выглядеть хуже. Авторы обычно берут 4 на 3, подстраивая значения под пропорции ваших изображений.
Зачем нужен параметр punch?Он регулирует контрастность декодированной заглушки: 1 — обычный вид, меньшие значения делают эффект мягче, большие — сильнее. Технически он масштабирует AC-компоненты вверх или вниз.
BlurHash годится только как заглушка на время загрузки?Нет. Им можно маскировать изображения без дорогих эффектов размытия (так делает Mastodon) и приближённо получать средние цвета участков картинки — средний цвет всего изображения это просто DC-компонента.
Кто использует BlurHash в продакшене?Wolt на iOS, Android и в вебе; Mastodon — для заглушек и скрытия чувствительных медиа; Signal — до загрузки фото- и видеосообщений; Jellyfin — для изображений фильмов и сериалов.
Creator
woltapp
Size
12 MB
Stars
17.1K
Updated
CommitMay 21
Age
7y
Commits · 90 Days