How can I decode a QR code from a local image file (.png) in JS?

Viewed 1532

I am trying to create a Cypress test that decodes a QR code from a webpage/pdf. I managed to take a screenshot using cy.screenshot(), but I don't find a way to extract the information from the QR image/PNG. Here is what I've tried using @nuintun/qrcode but I get an error: Failed to load image...

it('Takes QR Code Screenshot and Read QR Image', () => {
    cy.get('#image').screenshot('qrcode', {
        onAfterScreenshot($el, props) {
            console.log('========Test1======', props)
            qrcode
                .scan(props.path)
                .then(result => {
                    console.log('=====Test2=====', result);
                })
        }
    })

Instead of qrcode.scan I could use qrcode.decode, but I don't know how to transform the local PNG image to Uint8ClampedArray in a Cypress test using JavaScript. Any suggestions ?

decode(data: Uint8ClampedArray, width: number, height: number): DecoderResult
1 Answers

The decoder.scan method of @nuintun/qrcode use an Image class to create a (temporary) image element which it uses to do the scan.

Since it's an HTMLImageElement you can use it in the browser, but it does require a valid URL to the image.

However onAfterScreenshot($el, props) provides you with a full file path to the screenshot which cannot be accessed by the HTMLImageElement in the browser,
see the console error Not allowed to load local resource: file:///..../qrcode.png).

This is the way I was able to test it

import { Decoder } from '@nuintun/qrcode';

const qrcode = new Decoder();

it('decodes a qr-code', () => {

  cy.visit('my-page-with-qr-code')

  cy.get('img#image')                         // appropriate selector for image 
    .then($el => {
      const imagePath = $el[0].currentSrc;    // gives URL to image
                                              // e.g http://localhost:65206/app/qr-code.png
      qrcode.scan(imagePath).then(decode => {
        expect(decode.data).to.eq('https://www.cypress-qrcode.com')  // whatever qr is set to
      })
    })
})
Related