React library

QR detection

Read and decode QR codes from images in the browser with handleImageLoad, get the code's position, and score an image with getImageScanScore.

handleImageLoad decodes a QR code from an image element in the browser and returns its text. Use it to read codes from uploads, screenshots or photos without sending the image anywhere. For a ready-made drop zone, install the QR Code Scanner component, which is built on it.

FunctionReturnsNotes
handleImageLoad(img, size, returnFullData?)Promise<string | QRCode | "NO_QR">The decoded text, or the decoder's full result with returnFullData. "NO_QR" when nothing is found. Browser only
downloadImageWithBoundingBox(img, corners, filename)voidSaves the image as a PNG with the found code outlined in red
getImageScanScore(imageOrBlob, options?)Promise<ImageScanScoreResult>Decodes and scores an existing image. See Will it scan?
scanQRPixels(pixels, expected, options?)Promise<PixelScanResult>Checks that RGBA pixels decode to expected, in Node

Decode an uploaded image

components/qr-reader.tsx
"use client";

import { handleImageLoad } from "qrdx";
import { useState } from "react";

async function decodeFile(file: File): Promise<string | null> {
  const url = URL.createObjectURL(file);
  try {
    const image = new Image();
    image.src = url;
    await image.decode();
    const result = await handleImageLoad(image, image.naturalWidth);
    return typeof result === "string" && result !== "NO_QR" ? result : null;
  } finally {
    URL.revokeObjectURL(url);
  }
}

export function QrReader() {
  const [result, setResult] = useState("");

  async function onChange(event: React.ChangeEvent<HTMLInputElement>) {
    const file = event.target.files?.[0];
    if (!file) return;
    try {
      setResult((await decodeFile(file)) ?? "No QR code found");
    } catch {
      setResult("Could not read that image");
    }
  }

  return (
    <div>
      <input
        accept="image/*"
        aria-label="Image with a QR code"
        type="file"
        onChange={onChange}
      />
      {result ? <p>{result}</p> : null}
    </div>
  );
}

Pick a screenshot of a code and its link appears under the input. image.decode() waits for the file to load; handleImageLoad then draws the image on a canvas and runs jsQR, which it loads on demand so it stays out of bundles that never scan.

How detection works

handleImageLoad(img, size, returnFullData) tries the whole image first, then four crops (the bottom left, bottom right, top right and center regions at 65% of the image), each at six scales from 100% down to 10%. It returns the first decode that succeeds, so a code that fills a small part of a screenshot is still found. Very wide or tall images are downscaled first.

  • img must be a loaded <img>. Wait for decode() or the load event.
  • size is kept for compatibility with earlier releases and is ignored: the scales come from the image's own dimensions. Pass the image's width.
  • returnFullData returns jsQR's result object instead of the text.

A code that is blurred, cut off at the edges or lighter than its background (light modules on dark) is reported as "NO_QR".

Position and raw data

With returnFullData set, the result is the decoder's own object:

lib/decode-full.ts
import { handleImageLoad } from "qrdx";

const found = await handleImageLoad(image, image.naturalWidth, true);
if (found !== "NO_QR") {
  found.data; // "https://example.com"
  found.version; // 1 to 40
  found.binaryData; // the raw bytes, as number[]
  found.chunks; // the encoded segments and their modes
  found.location.topLeftCorner; // { x, y } in the image's pixels, and the other three corners
}

downloadImageWithBoundingBox draws the code's outline on the original image and saves it, which helps when a photo decodes to something unexpected. The corners go in the order top left, top right, bottom left, bottom right:

lib/debug-detection.ts
import { downloadImageWithBoundingBox, handleImageLoad } from "qrdx";

const found = await handleImageLoad(image, image.naturalWidth, true);
if (found !== "NO_QR") {
  const { topLeftCorner, topRightCorner, bottomLeftCorner, bottomRightCorner } = found.location;
  downloadImageWithBoundingBox(
    image,
    [topLeftCorner, topRightCorner, bottomLeftCorner, bottomRightCorner],
    "found-code.png"
  );
}

Score an image instead of only decoding it

getImageScanScore decodes an existing image and also reports how reliably it would scan: decode at three sizes with camera-like blur, contrast, polarity, quiet zone and resolution. It takes a File, a Blob or an <img>.

lib/score-image.ts
import { getImageScanScore } from "qrdx";

const { data, score, grade, checks } = await getImageScanScore(file);
// data: "https://example.com" or null
// score: 0 to 100, grade: "great" | "ok" | "risky" | "fails"

The scan checker is built on it. In Node, scanQRPixels(pixels, expected) checks that RGBA pixels (from decodePNGPixels or sharp().raw()) decode to a known value.

If something goes wrong

  • Every image returns "NO_QR". The image was not loaded when you called the function. Await image.decode() first. If it is loaded, the code may be too small, blurred, cropped or inverted; try a sharper image with the whole code and some margin around it.
  • handleImageLoad is called on the server. It needs a canvas. Call it from a Client Component or an event handler, or use scanQRPixels in Node.
  • The outline from downloadImageWithBoundingBox is a bow tie. The corners are in the wrong order. Pass top left, top right, bottom left, bottom right.

Was this page helpful?

Last updated on

On this page