Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aibrahim3546/7a3c7405c0a090889774ee29b1d87db7 to your computer and use it in GitHub Desktop.
Save aibrahim3546/7a3c7405c0a090889774ee29b1d87db7 to your computer and use it in GitHub Desktop.
Decode QR code from image in react native
import jsQR from 'jsqr' // required package
import Jimp from 'jimp' // required package
const BASE64_MARKER = ';base64,'
const base64ToArrayBuffer = (dataURI) => {
const base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length
const base64 = dataURI.substring(base64Index)
const binaryString = window.atob(base64)
const len = binaryString.length
const bytes = new Uint8Array(len)
for (let i = 0; i < len; i += 1) {
bytes[i] = binaryString.charCodeAt(i)
}
return bytes.buffer
}
/*
params: imageBase64, type string
convert image to base64 using rn-fetch-blob (https://github.com/joltup/rn-fetch-blob)
*/
export const decodeQRCodeFromImage = async (imageBase64): Promise<string> => {
const future = new Promise<string>(async (resolve, reject) => {
const arrayBuffer = base64ToArrayBuffer(imageBase64)
await Jimp.read(arraybuffer, (err, img) => {
if (err) {
return reject(err)
}
const qrCodeImageArray = new Uint8ClampedArray(img.bitmap.data.buffer)
const qrCodeResult = jsQR(
qrCodeImageArray,
img.bitmap.width,
img.bitmap.height,
)
if (qrCodeResult) {
return resolve(qrCodeResult.data)
}
return reject(new Error('WXGetQRCode() qrCode decode fail'))
})
})
try {
const qrCode = await future
return Promise.resolve(qrCode)
} catch (err) {
console.error(err)
return Promise.reject(err)
}
}
// Usage
const getQRCodeData = async () => {
const imageBase64 = 'image base64 string here'
const qrCodeData = await decodeQRCodeFromImage(imageBase64)
console.log('DATA => , qrCodeData)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment