Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/mrousavy/react-native-blurhash
🖼️ A library to show colorful blurry placeholders while your content loads.
https://github.com/mrousavy/react-native-blurhash
algorithm blurhash component encoder hacktoberfest image javascript kotlin library loading native-module node npm placeholder react react-native swift typescript ui ux
Last synced: 5 days ago
JSON representation
🖼️ A library to show colorful blurry placeholders while your content loads.
- Host: GitHub
- URL: https://github.com/mrousavy/react-native-blurhash
- Owner: mrousavy
- License: mit
- Created: 2020-06-08T09:08:36.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2024-09-09T10:59:01.000Z (3 months ago)
- Last Synced: 2024-10-29T11:06:14.498Z (about 2 months ago)
- Topics: algorithm, blurhash, component, encoder, hacktoberfest, image, javascript, kotlin, library, loading, native-module, node, npm, placeholder, react, react-native, swift, typescript, ui, ux
- Language: Kotlin
- Homepage: https://blurha.sh
- Size: 5.14 MB
- Stars: 1,949
- Watchers: 8
- Forks: 71
- Open Issues: 34
-
Metadata Files:
- Readme: README.md
- Contributing: CONTRIBUTING.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
- awesome-react-native - react-native-blurhash ★105 - Give your users the loading experience they want. (Components / UI)
- awesome-react-native - react-native-blurhash ★105 - Give your users the loading experience they want. (Components / UI)
README
# Blurhash
> 🖼️ Give your users the loading experience they want.
Install via [npm](https://www.npmjs.com/package/react-native-blurhash):
```sh
npm i react-native-blurhash
npx pod-install
```[![npm](https://img.shields.io/npm/v/react-native-blurhash?color=%238B83E6)](https://www.npmjs.com/package/react-native-blurhash)
[![npm](https://img.shields.io/npm/dt/react-native-blurhash?color=%238B83E6)](https://www.npmjs.com/package/react-native-blurhash)[![GitHub followers](https://img.shields.io/github/followers/mrousavy?label=Follow%20%40mrousavy&style=social)](https://github.com/mrousavy?tab=followers)
[![Twitter Follow](https://img.shields.io/twitter/follow/mrousavy?label=Follow%20%40mrousavy&style=social)](https://twitter.com/mrousavy)**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](https://github.com/woltapp/blurhash), which also includes an [algorithm explanation](https://github.com/woltapp/blurhash/blob/master/Algorithm.md).
## Expo
- ✅ You can use this library with [Development Builds](https://docs.expo.dev/development/introduction/). No config plugin is required.
- ❌ This library can't be used in the "Expo Go" app because it [requires custom native code](https://docs.expo.dev/workflow/customizing/).## 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:
- 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, ...)
- The function on my server then
- generates a blurhash from the image in the payload using the C encoder
- stores the post data (including the generated blurhash string) in my database
- uploads the image to a content delivery network (e.g. AWS)
- 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'sonLoadEnd
function has been called.
Note: You can also use the react-native-blurhash encoder to encode straight from your React Native App!
## Usage
The `` 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, use16
for large lists, otherwise you can increase it to32
.
See: performance
❌
32
decodeHeight
number
The height (resolution) to decode to. Higher values decrease performance, use16
for large lists, otherwise you can increase it to32
.
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 givenblurhash
string.
❌
undefined
onLoadEnd
() => void
A callback to call when the Blurhash successfully decoded the givenblurhash
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 themessage
parameter to get the error message.
❌
undefined
AllView
props
ViewProps
All properties from the React NativeView
. Usestyle.width
andstyle.height
for display-sizes. Also,style.borderRadius
is natively supported on iOS.
❌
{}
Example Usage:
```tsx
import { Blurhash } from 'react-native-blurhash';export default function App() {
return (
);
}
```> See the [example](example/) App for a full code example.
iOS Screenshot
Android 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:
```ts
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!
```ts
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`.
```ts
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 `` component caches the rendered Blurhash (Image) as long as the `blurhash`, `decodeWidth`, `decodeHeight` and `decodePunch` properties stay the same. Because unmounting the `` 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:
```ts
Blurhash.clearCosineCache()
```> Note: At the moment, cosine operations are only cached on Android. Calling `clearCosineCache()` is a no-op on other platforms.
## Resources
* [this medium article.](https://teabreak.e-spres-oh.com/swift-in-react-native-the-ultimate-guide-part-2-ui-components-907767123d9e) jesus christ amen thanks for that
* [Native Modules documentation](https://reactnative.dev/docs/native-modules-ios.html), especially the [Swift part](https://reactnative.dev/docs/native-modules-ios.html#exporting-swift)
* [This cheatsheet gist](https://gist.github.com/chourobin/f83f3b3a6fd2053fad29fff69524f91c) thank you [**@chourobin**](https://github.com/chourobin).
* [DylanVann/react-native-fast-image](https://github.com/DylanVann/react-native-fast-image) as a reference for native UI modules
* [woltapp/blurhash](https://github.com/woltapp/blurhash) of course