cozmo / jsQR

A pure javascript QR code reading library. This library takes in raw images and will locate, extract and parse any QR code found within.
https://cozmo.github.io/jsQR/
Apache License 2.0
3.73k stars 607 forks source link

Can't read any codes from input element #215

Closed randomprogramming closed 2 years ago

randomprogramming commented 2 years ago
<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:

frame

randomprogramming commented 2 years ago

Stupid mistake, adding:

        canvas.height = img.naturalHeight;
        canvas.width = img.naturalWidth;

Fixed the problem...

GitHub30 commented 1 year ago

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;
}