如何解码JS中本地图像文件(.png)中的二维码



我正在尝试创建一个Cypress测试,用于解码网页/pdf中的二维码。我设法用cy.screenshot((拍了一张截图,但我找不到从QR图像/PNG中提取信息的方法。以下是我尝试使用@nuintun/qrcode的内容,但我收到了一个错误:无法加载图像。。。

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

我可以使用qrcode.decode代替qrcode.scan,但我不知道如何在Cypress测试中使用JavaScript将本地PNG图像转换为Uint8ClampedArray。有什么建议吗?

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

@nuintun/qrcode的decoder.scan方法使用Image类创建一个用于进行扫描的(临时(图像元素。

由于它是HTMLImageElement,您可以在浏览器中使用它,但它确实需要图像的有效URL。

但是,onAfterScreenshot($el, props)为您提供了屏幕截图的完整文件路径,浏览器中的HTMLImageElement无法访问该路径,
请参阅控制台错误不允许加载本地资源:file:///..../qrcode.png(。

这是我测试的方法

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

最新更新