[英]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我有从Expo ImagePicker 组件返回的 base64 格式的图像数据,我想将其转换为 [r0, g0, b0, a0, r1, g1, b1, a1, ...] 形式的 RGBA 像素值的 Uint8ClampedArray,因为它是jsQR 库接受的唯一输入
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任何帮助将不胜感激
I'm guessing your base64-encoded URI is actually a PNG, so you could do the following:我猜你的 base64 编码的 URI 实际上是一个 PNG,所以你可以执行以下操作:
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
The solution that I found is as follows:我找到的解决方案如下:
it requires the usage of typedarray , Buffer , jpeg-js它需要使用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];
}
New answer for react native:反应原生的新答案:
this package should do the trick.这个包应该可以解决问题。 let me know if it works.
让我知道它是否有效。
https://www.npmjs.com/package/get-image-data https://www.npmjs.com/package/get-image-data
OLD ASNWER FOR BROWSER:浏览器的旧 ASNWER:
First put the base64 img in a canvas like described here:首先将 base64 img 放入画布中,如下所述:
Base64 PNG data to HTML5 canvas Base64 PNG 数据到 HTML5 画布
Then apply ImageData
on your canvas
( https://developer.mozilla.org/en-US/docs/Web/API/ImageData )然后在
canvas
上应用ImageData
( https://developer.mozilla.org/en-US/docs/Web/API/ImageData )
This should give you the desired result.这应该会给你想要的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.