joyce
joyce

Reputation: 183

React Native base64 Image to Uint8ClampedArray

I had functionality to pick an image of QRcode from CameraRoll of Android and iOS in react-native and once the user had picked an image. I will use something like jsQR to decode that and validate if its a real qr code or not.

But on jsQR lib they said that they need to accept Uint8ClampedArray to decode the image and read the qr. So I already have a function to get the base64 image. But can't find on how to convert it properly to Uint8ClampedArray.

Here is my code below:

const handleImportScan = useCallback(async () => {
    try {
      const base64Image = await RNFS.readFile(
        photos[selected].node.image.uri,
        'base64',
      );
      console.log('base64img:', base64Image);
      // First argument below should be a 'Uint8ClampedArray'
      const code = jsQR(base64Image, width, height);
      if (code) {
        console.log('Found QR code', code);
      }
    } catch (error) {
      console.log('err:', error);
    }
  }, [photos, selected]);

I'm trying to find a library or third-party to convert my base64 image to Uint8ClampedArray

Mostly I save the user qr generate images using PNG.

Appreciate it if someone could help. Thanks

Upvotes: 1

Views: 897

Answers (1)

reck753
reck753

Reputation: 21

Note that base64data should be base64 encoded image not uri. (eg. without 'data:image/png;base64,', if you have uri)

const byteCharacters = atob(base64data);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8ClampedArray(byteNumbers);

Upvotes: 2

Related Questions