Can't read any codes from input element
randomprogramming opened this issue · 2 comments
randomprogramming commented
<input
type="file"
accept="application/pdf,image/jpeg,image/png"
onChange={handleFileChange} />
async function handleFileChange(e: any) {
if ((e.target.files[0] as File).type.includes("image/")) {
console.log(e.target.files[0]);
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const img = new Image();
img.src = URL.createObjectURL(e.target.files[0]);
console.log(URL.createObjectURL(e.target.files[0]));
img.onload = () => {
ctx!.drawImage(img, 0, 0);
const imageData = ctx!.getImageData(
0,
0,
img.naturalWidth,
img.naturalHeight
);
console.log(imageData.data);
const code = jsQR(imageData.data, img.naturalWidth, img.naturalHeight);
console.log(code);
};
return;
}
}
imageData.data is defined when logging
code is logged as null
Sample QR that doesn't work with this approach:
randomprogramming commented
Stupid mistake, adding:
canvas.height = img.naturalHeight;
canvas.width = img.naturalWidth;
Fixed the problem...
GitHub30 commented
Thank you so much, You've been very helpful..
https://codepen.io/04/pen/xxmwXNe?editors=1010
async function scanQRFromFile(file) {
const img = new Image();
img.src = URL.createObjectURL(file);
await new Promise((resolve) => img.addEventListener("load", resolve));
const canvas = new OffscreenCanvas(img.naturalWidth, img.naturalHeight);
const ctx = canvas.getContext("2d");
ctx.imageSmoothingEnabled = false;
ctx.drawImage(img, 0, 0);
const imageData = ctx.getImageData(0, 0, img.naturalWidth, img.naturalHeight);
return jsQR(imageData.data, img.naturalWidth, img.naturalHeight)?.data;
}