jsQR icon indicating copy to clipboard operation
jsQR copied to clipboard

Restrict search bounds?

Open eventualbuddha opened this issue 4 years ago • 1 comments

Rather than requiring a new cropped image, it would be nice if I could specify the search bounds if I have a larger image but I know roughly where the QR code should be. Is this a feature you'd consider? If so, I may have time to make a PR for it.

eventualbuddha avatar Apr 29 '20 19:04 eventualbuddha

Hey! I'm of 2 minds here. On one hand, I think the API of taking in an image and returning any found QR codes is the simplest, and cropping an image doesn't really feel like it's the job of jsQR, and should be as relatively simple to do, something like:

function crop(originalImageData: Uint8ClampedArray, originalWidth: number, originalHeight: Number, topLeft: Point, bottomRight: Point) {
  const newWidth = bottomRight.x - topLeft.x;
  const newHeight = bottomRight.y - topLeft.y;

  const croppedImageData = new Uint8ClampedArray(newWidth * newHeight * 4);

  for (let y = 0; y < newHeight; y++) {
    const stride = originalImageData.subarray(
      (((y + topLeft.y) * originalWidth + topLeft.x) * 4) + 0, // start of the stride in the original image coordinates
      (((y + topLeft.y) * originalWidth + topLeft.x + newWidth) * 4) + 4 // end of the stride in the original image coordinates
    )
    croppedImageData.set(stride, y * newWidth);
  }
  return croppedImageData;
}

Which would allow for cropping the image with N memory reads/writes, where N is the height of the new image.

That said, this code is probably more complex than would be expected for most consumers to write correctly, especially in an efficient manner, and I think we can actually do better in jsQR. By changing binarizer here we can basically just look at the part of the image we care about, without doing any additional reads/writes/initializations.

As such, I'm open to putting it into jsQR, but I'm probably won't prioritize it myself. If you were to make a PR I'd be happy to accept it.

cozmo avatar Apr 29 '20 23:04 cozmo