• Stars
    star
    1,568
  • Rank 28,661 (Top 0.6 %)
  • Language
    Kotlin
  • License
    MIT License
  • Created almost 4 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🖼️ A library to show colorful blurry placeholders while your content loads.
This library helped you? Consider sponsoring!

Blurhash

🖼️ Give your users the loading experience they want.

Install via npm:

npm i react-native-blurhash
npx pod-install

npm npm

GitHub followers Twitter Follow

BlurHash is a compact representation of a placeholder for an image. Instead of displaying boring grey little boxes while your image loads, show a blurred preview until the full image has been loaded.

The algorithm was created by woltapp/blurhash, which also includes an algorithm explanation.

Turn grey image boxes into colorful blurred images

Expo

Example Workflow

    In order to use the Blurhash component, you have to already have a Blurhash string. See the blurha.sh page to create example strings.

    This is how I use it in my project:

  1. A user creates a post by calling a function on my server which expects a payload of an image and some post data (title, description, ...)
  2. The function on my server then
    1. generates a blurhash from the image in the payload using the C encoder
    2. stores the post data (including the generated blurhash string) in my database
    3. uploads the image to a content delivery network (e.g. AWS)
  3. Now everytime a user loads a feed of posts from my database, I can immediately show a <Blurhash> component (with the post's .blurhash property) over my <Image> component, and fade it out once the <Image> component's onLoadEnd function has been called.

  4. Note: You can also use the react-native-blurhash encoder to encode straight from your React Native App!

Usage

The <Blurhash> component has the following properties:

Name Type Explanation Required Default Value
blurhash string The blurhash string to use. Example: LGFFaXYk^6#M@-5c,1J5@[or[Q6. ✅ undefined
decodeWidth number The width (resolution) to decode to. Higher values decrease performance, use 16 for large lists, otherwise you can increase it to 32.
See: performance
❌ 32
decodeHeight number The height (resolution) to decode to. Higher values decrease performance, use 16 for large lists, otherwise you can increase it to 32.
See: performance
❌ 32
decodePunch number Adjusts the contrast of the output image. Tweak it if you want a different look for your placeholders. ❌ 1.0
decodeAsync boolean Asynchronously decode the Blurhash on a background Thread instead of the UI-Thread.
See: Asynchronous Decoding
❌ false
resizeMode 'cover' | 'contain' | 'stretch' | 'center' Sets the resize mode of the image. (no, 'repeat' is not supported.)
See: Image::resizeMode
❌ 'cover'
onLoadStart () => void A callback to call when the Blurhash started to decode the given blurhash string. ❌ undefined
onLoadEnd () => void A callback to call when the Blurhash successfully decoded the given blurhash string and rendered the image to the <Blurhash> view. ❌ undefined
onLoadError (message?: string) => void A callback to call when the Blurhash failed to load. Use the message parameter to get the error message. ❌ undefined
All View props ViewProps All properties from the React Native View. Use style.width and style.height for display-sizes. Also, style.borderRadius is natively supported on iOS. ❌ {}

Example Usage:

import { Blurhash } from 'react-native-blurhash';

export default function App() {
  return (
    <Blurhash
      blurhash="LGFFaXYk^6#M@-5c,1J5@[or[Q6."
      style={{flex: 1}}
    />
  );
}

See the example App for a full code example.

iOS Screenshot Android Screenshot
iOS Demo Screenshot Android Demo Screenshot

Average Color

If your app is really colorful you might want to match some containers' colors to the content's context. To achieve this, use the getAverageColor function to get an RGB value which represents the average color of the given Blurhash:

const averageColor = Blurhash.getAverageColor('LGFFaXYk^6#M@-5c,1J5@[or[Q6.')

Encoding

This library also includes a native Image encoder, so you can encode Images to blurhashes straight out of your React Native App!

const blurhash = await Blurhash.encode('https://blurha.sh/assets/images/img2.jpg', 4, 3)

Because encoding an Image is a pretty heavy task, this function is non-blocking and runs on a separate background Thread.

Validation

If you need to validate a blurhash string, you can use isValidBlurhash.

const result = Blurhash.isValidBlurhash('LGFFaXYk^6#M@-5c,1J5@[or[Q6.')
if (result.isValid) {
  console.log(`Blurhash is valid!`)
} else {
  console.log(`Blurhash is invalid! ${result.reason}`)
}

Performance

The performance of the decoders is really fast, which means you should be able to use them in collections quite easily. By increasing the decodeWidth and decodeHeight props, the time to decode also increases. I'd recommend values of 16 for large lists, and 32 otherwise. Play around with the values but keep in mind that you probably won't see a difference when increasing it to anything above 32.

Asynchronous Decoding

Use decodeAsync={true} to decode the Blurhash on a separate background Thread instead of the main UI-Thread. This is useful when you are experiencing stutters because of the Blurhash's decoder - e.g.: in large Lists.

Threads are re-used (iOS: DispatchQueue, Android: kotlinx Coroutines).

Caching

Image

A <Blurhash> component caches the rendered Blurhash (Image) as long as the blurhash, decodeWidth, decodeHeight and decodePunch properties stay the same. Because unmounting the <Blurhash> component clears the cache, re-mounting it will cause it to decode again.

Cosine Operations

Cosine operations get cached in memory to avoid expensive re-calculation (~24.576 cos(...) calls per 32x32 blurhash). Since this can affect memory usage, you can manually clear the cosine array cache by calling:

Blurhash.clearCosineCache()

Note: At the moment, cosine operations are only cached on Android. Calling clearCosineCache() is a no-op on other platforms.

Resources

Buy Me a Coffee at ko-fi.com

More Repositories

1

react-native-vision-camera

📸 A powerful, high-performance React Native Camera library.
Swift
6,320
star
2

react-native-mmkv

⚡️ The fastest key/value storage for React Native. ~30x faster than AsyncStorage!
C++
4,903
star
3

react-native-multithreading

🧵 Fast and easy multithreading for React Native using JSI
C++
1,049
star
4

Colorwaver

🎨 An app to detect color palettes in the real world - powered by VisionCamera
TypeScript
548
star
5

react-native-jsi-image

🖼️ A writeable in-memory Image JSI Host Object
C++
267
star
6

react-native-tracking-transparency

🕵️ A React Native Library for interacting with the tracking API from iOS 14.
Java
208
star
7

react-native-google-nearby-messages

📲 Communicate with nearby devices using Bluetooth, BLE, WiFi and near-ultrasonic audio. Broadcast and receive small payloads (like strings) using the easy-to-use React Native API!
Kotlin
173
star
8

react-native-jsi-contacts

A contacts library for React Native using JSI
C++
140
star
9

AnimatedGif

📼 A high performance .NET library for reading and creating animated GIFs
C#
127
star
10

react-native-blob-jsi-helper

A React Native library for accessing an ArrayBuffer of a Blob instance.
C++
118
star
11

react-native-jsi-library-template

Template for React Native JSI Libraries Ă  la Marc
C++
110
star
12

clean-rn

A simple CLI tool to clean all React Native caches in your project.
JavaScript
109
star
13

vision-camera-image-labeler

VisionCamera Frame Processor Plugin to label images using MLKit Vision
Java
97
star
14

ImgurSniper

📷 A quick and easy Image, Screenshot and Screen recording sharing tool
C#
85
star
15

react-native-style-utilities

Fully typed hooks and utility functions for the React Native StyleSheet API
JavaScript
78
star
16

Hotkeys

🔤 A small C# (.NET) Library which allows binding of global HotKeys to any Application's Windows (including Windows Apps such as explorer.exe), even in Background. (using P/Invokes)
C#
71
star
17

react-native-notification-badge

🔴 A notification badge count manager for React Native
Swift
47
star
18

react-native-pressable-opacity

A <PressableOpacity> and a supercharged <NativePressableOpacity> components for React Native
TypeScript
46
star
19

GenericProtocol

⚡️ A fast TCP event based buffered server/client protocol for transferring data over the (inter)net in .NET 🌐
C#
42
star
20

DiscordMusicBot

A Discord Bot for playing YouTube music.
C#
41
star
21

react-native-pressable-scale

A <PressableScale> and a supercharged <NativePressableScale> components for React Native
TypeScript
39
star
22

StorageBenchmark

Benchmark App to compare different storage libraries (MMKV, AsyncStorage, WatermelonDB, RealmDB, SQLite)
Java
29
star
23

react-native-screen-corner-radius

📱 A React Native library to get the Device's Screen's corner radius
Java
27
star
24

BrabeNetz

🧠 A fast and clean supervised neural network in C++, capable of effectively using multiple cores
C++
26
star
25

Toast

🍞 The rounded and animated Android Toast for .NET WPF/XAML
C#
26
star
26

Fiddle

📜 A lightweight code editor for editing, compiling and running code snippets/scripts supporting multiple languages and rich GUI
C
23
star
27

Jellyfish

🐟 An incredibly lightweight and type safe MVVM library for .NET WPF, Silverlight, Xamarin and UWP
C#
20
star
28

PostShot

📷 An easy to use, lightning fast and modern screenshot and screen-recording tool powered by C++ and Qt
C++
17
star
29

vision-camera-resize-plugin

A VisionCamera Frame Processor plugin for fast buffer resizing
Objective-C
17
star
30

WebUntisSharp

⏰ A Wrapper of the WebUntis JSON API for .NET
C#
14
star
31

pipestate

🏦 A minimal state management library for React.
TypeScript
13
star
32

gimp-rpc

A GIMP plugin to display Discord Rich Presence made with C
C
11
star
33

react-native-sectioned-slider

An iOS 11 Control Center inspired Slider for React Native
Ruby
10
star
34

ClipboardMonitor

A small C# Library for Monitoring Clipboard with P/Invokes (e.g.: Clipboard Content Changed event)
C#
9
star
35

GameFinder

🎮 An application for finding games to play you and your friends have on Steam
C#
8
star
36

QHotkeys

🔠 A small and lightweight cross platform C++ library implementing a system-wide hotkey system for Qt
C++
7
star
37

Keepr

A Tinder-like swipe view to keep or remove pictures from a photoshoot with extra comparison features
TypeScript
7
star
38

BmpPwd

🔐 BmpPwd is a .NET Class Library for overloadable en/decrypting strings or binary data to a System.Drawing.Image
C#
7
star
39

MaterialDesignWindowsDialogs

A new Theme (Android Material Design) for Windows Message Boxes (by hooking)
C#
7
star
40

shared-registry

Shared-Registry allows you to share objects between instances without introducing memory leaks.
TypeScript
6
star
41

dotfiles

My personal minimalistic dotfiles (.vimrc, .zshrc, .oh-my.zsh, custom scripts, ..)
Shell
6
star
42

mrousavy

✨ it's lit ✨
6
star
43

MetaLog

📝 Simple, yet effective, logging with Metadata CallerInfo for creating beautiful Log files in C#/VB .NET
C#
5
star
44

SchoolTool

📓 An App to watch your timetable and get notified of changes.
C#
3
star
45

HankHill

A discord bot for pixelating and jpegifying images
C#
3
star
46

maconvert

Easily convert .svg files to .png files
JavaScript
3
star
47

TinyRocket

A 2D Endless Unity Game; Fly up high and beat highscores with your customizable and upgradeable Rocket!
C#
3
star
48

Cirilla

🤖 Cirilla - The swiss army knife discord bot supporting many commands and systems
C#
3
star
49

Morph

🛠 A fast .NET Standard Class Library for parsing results from an SQL query to .NET objects to eliminate risky column-index hardcoding
C#
2
star
50

QPastebin

A quick Pastebin-uploader shell script using curl and the Pastebin REST API
Shell
2
star
51

QuantumSnippets

Snippets, Examples or Test code for Quantum Computers written in the Microsoft Quantum Computer Programming Language Q#
C#
1
star
52

discord-cli

CLI for discord bots
JavaScript
1
star
53

ModellbaumesseRoboter

Roboter fĂźr Modellbaumesse 2016 (TGM 3DHIT)
C++
1
star
54

Vertaler

📖 A pop-up tray application to instantly translate something from your clipboard using Google Translate
C#
1
star
55

pokecord-guesser

Guesser for Pokecord using Discord API and reverse image lookup
HTML
1
star
56

ModWnd

👺 A daemon to move any Window from within it's body (child area) while holding a modifier key (Windows/Alt)
C++
1
star
57

VisionCameraDemo

Demo for using VisionCamera + zooming
TypeScript
1
star