如何在React Native中从文件路径(而不是相机)读取QRCode?我正在使用 react-native v0.57.1
编辑1:
在@joshkmartinez的帮助下,我能够编写此方法:
getImageInfo(path) {
return new Promise(resolve => {
Image.getSize(`file://${path}`, (width, height) => {
ImgToBase64.getBase64String(`file://${path}`).then(base64String => {
var raw = window.atob(base64String);
var rawLength = raw.length;
var imageData = new Uint8ClampedArray(new ArrayBuffer(rawLength));
for (var i = 0; i < rawLength; i++) {
imageData[i] = raw.charCodeAt(i);
}
resolve({
width,
height,
imageData,
});
});
});
})
}
并使用:
this.getImageInfo(path).then(imageInfo => {
jsQR(imageInfo.imageData, imageInfo.width, imageInfo.height).then(qrcode => {
console.log(qrcode);
});
});
但是jsQR返回错误Malformed data passed to binarizer
也许在将文件转换为Base64时出现了问题,我正在使用react-native-image-base64来转换图像
编辑2:
经过2天的研究,我能够使用此方法将图像转换为react-native-fs,Buffer和jpeg-js:
decodeImageData(image) {
var imagePath = `${image.filePath}/${image.fileFullName}`;
return new Promise(resolve => {
RNFS.readFile(imagePath, 'base64').then(base64string => {
const imageData = Buffer.from(base64string, 'base64');
var rawImageData = JPEG.decode(imageData);
var clampedArray = new Uint8ClampedArray(rawImageData.data.length);
for (var i = 0; i < rawImageData.data.length; i++) {
clampedArray[i] = rawImageData.data[i];
}
resolve({
width: rawImageData.width,
height: rawImageData.height,
data: clampedArray,
});
});
});
}
仅是发现jsQR无法读取我的任何qrcode(它仅向所有qrcode返回null)
我在这里还缺少什么吗?也许是在图像转换,解码等过程中?
答案 0 :(得分:0)
我最初在使用 jsQR 时遇到了同样的问题。我的目标是从图库中选择的图像中检测 QR 码。
我通过使用“react-native-image-picker”和“rn-qr-generator”找到了一个解决方案。
// ... other imports ...
import { launchImageLibrary } from 'react-native-image-picker';
import RNQRGenerator from 'rn-qr-generator';
// ...
openQRCodeFromGallery() {
const galleryOptions = {
mediaType: 'photo',
includeBase64: true,
};
launchImageLibrary(galleryOptions, (response) => {
if (!response || response.didCancel || !response.base64) {
return;
}
const { base64 } = response;
RNQRGenerator.detect({
base64: base64,
})
.then((detectedQRCodes) => {
const { values } = detectedQRCodes; // Array of detected QR code values. Empty if nothing found.
// do your stuff
})
.catch((error) => {
// handle errors
});
});
}
使用的版本: