mrousavy
mrousavy

Reputation: 1117

React Native: Display array of pixels in Image component (blurhash)

How would I display an array of pixels (UInt8ClampedArray or UInt8Array) in a React Native <Image> component?

I'm using the blurhash library to decode a string my web-endpoint has sent me, let's say UAKBgy~qM|IU0000-;M{_3t5D%RQ00_3xaIU, which I want to render as a blurred Image in my View.

I've tried setting it to the uri property of the Image source, but the image just didn't display anything.

import { decode } from 'blurhash';
// ...
const myHash = 'UAKBgy~qM|IU0000-;M{_3t5D%RQ00_3xaIU';
const result = decode(myHash, 32, 32);
const base64 = `data:image/jpeg;base64,${result.toString()}`;
const imgSource = { uri: base64 };
// ...
<Image source={imgSource} ...

The decode function returns an UInt8ClampedArray, which cannot be used as an Image source.

Can anyone help me out here?

Upvotes: 1

Views: 837

Answers (2)

Mathieu CAROFF
Mathieu CAROFF

Reputation: 1462

I believe that React-Native-Skia can do that. Here's an example from the documentation:

import { Skia, AlphaType, ColorType } from "@shopify/react-native-skia";
 
const pixels = new Uint8Array(256 * 256 * 4);
pixels.fill(255);
let i = 0;
for (let x = 0; x < 256; x++) {
  for (let y = 0; y < 256; y++) {
    pixels[i++] = (x * y) % 255;
  }
}
const data = Skia.Data.fromBytes(pixels);
const img = Skia.Image.MakeImage(
  {
    width: 256,
    height: 256,
    alphaType: AlphaType.Opaque,
    colorType: ColorType.RGBA_8888,
  },
  data,
  256 * 4
);

See https://shopify.github.io/react-native-skia/docs/images#makeimage

Upvotes: 0

mrousavy
mrousavy

Reputation: 1117

So I've spent a long time trying to figure this out. I've ended up creating my own native UI module which decodes the image natively, and renders it using native Image components (UIImageView on iOS and ReactImageView on Android).

Check it out at: mrousavy/react-native-blurhash

Upvotes: 2

Related Questions