“Build a web application to detect QR code from an image.”
Introduction
This task involves creating a simple web application that can detect and decode QR codes from uploaded images. We will use the jsQR
library, which is a popular JavaScript library for QR code detection and decoding.
Implementation Details
- HTML:
- Includes an image upload feature and a display area for the QR code result.
- JavaScript:
- Reads the uploaded image and converts it to a canvas for processing.
- Uses the
jsQR
library to detect and decode the QR code from the image.
- Testing:
- Test the functionality with different QR code images.
Here’s the implementation:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>QR Code Detection</title> <style> body { font-family: Arial, sans-serif; text-align: center; margin: 20px; } #qr-result { margin-top: 20px; font-size: 1.2em; color: green; } </style> <script src="https://cdn.jsdelivr.net/npm/jsqr/dist/jsQR.min.js"></script> </head> <body> <h2>QR Code Detection</h2> <p>Upload an image containing a QR code:</p> <input type="file" id="image-upload" accept="image/*"> <canvas id="qr-canvas" style="display:none;"></canvas> <p id="qr-result">QR Code Result: <span id="qr-output">None</span></p> <script> const fileInput = document.getElementById('image-upload'); const canvas = document.getElementById('qr-canvas'); const output = document.getElementById('qr-output'); const qrResult = document.getElementById('qr-result'); const context = canvas.getContext('2d'); fileInput.addEventListener('change', async (event) => { const file = event.target.files[0]; if (!file) return; const img = new Image(); img.onload = () => { // Set canvas size to the image size canvas.width = img.width; canvas.height = img.height; context.drawImage(img, 0, 0, img.width, img.height); // Extract image data and scan for QR code const imageData = context.getImageData(0, 0, canvas.width, canvas.height); const qrCode = jsQR(imageData.data, canvas.width, canvas.height); if (qrCode) { output.textContent = qrCode.data; qrResult.style.color = "green"; } else { output.textContent = "No QR Code detected."; qrResult.style.color = "red"; } }; img.src = URL.createObjectURL(file); }); </script> </body> </html>
How It Works
- Upload Image:
- The user uploads an image containing a QR code.
- Process Image:
- The script renders the image onto a hidden
<canvas>
element. - Extracts pixel data from the canvas for QR code detection.
- The script renders the image onto a hidden
- Detect QR Code:
- The
jsQR
library processes the image data and attempts to decode a QR code. - If successful, the decoded text is displayed. If not, an error message is shown.
- The
Testing
- Open the HTML file in a browser.
- Upload a valid QR code image using the “Choose File” input.
- Observe the decoded QR code or the error message in the result section.
- Test on different browsers and with various QR code images.