Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image Base64 string to Uint8ClampedArray

I have imagedata in base64 format returned from Expo ImagePicker component, and I want to convert it to An Uint8ClampedArray of RGBA pixel values in the form [r0, g0, b0, a0, r1, g1, b1, a1, ...], cause it's the only input accepted by jsQR library

I tried this, but did not work:

const dataURItoBlob = byteString  => {

  // write the bytes of the string to a typed array
  var ia = new Uint8ClampedArray(byteString.length);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }

  return ia;
};

any help will be highly appreciated

like image 887
Hend El-Sahli Avatar asked Aug 21 '18 12:08

Hend El-Sahli


2 Answers

I'm guessing your base64-encoded URI is actually a PNG, so you could do the following:

const {PNG} = require('pngjs');
const jsqr = require('jsqr');

const dataUri = 'data:image/png;base64,ABCDEFYOURIMAGEHEREABCDEF';
const png = PNG.sync.read(Buffer.from(dataUri.slice('data:image/png;base64,'.length), 'base64'));
const code = jsqr(Uint8ClampedArray.from(png.data), png.width, png.height);

// code.data now contains the URL string encoded by the QR code
like image 63
Oleg Vaskevich Avatar answered Oct 27 '22 09:10

Oleg Vaskevich


The solution that I found is as follows:

it requires the usage of typedarray, Buffer, jpeg-js

var Uint8ClampedArray = require('typedarray').Uint8ClampedArray;
const Buffer = require('buffer').Buffer;
global.Buffer = Buffer; // very important
const jpeg = require('jpeg-js');


const jpegData = Buffer.from(base64, 'base64');
var rawImageData = jpeg.decode(jpegData);

var clampedArray = new Uint8ClampedArray(rawImageData.data.length);
// manually fill Uint8ClampedArray, cause Uint8ClampedArray.from function is not available in react-native
var i;
for (i = 0; i < rawImageData.data.length; i++) {
  clampedArray[i] = rawImageData.data[i];
}
like image 35
Hend El-Sahli Avatar answered Oct 27 '22 08:10

Hend El-Sahli