Skip to main content

How to decode a QR code from an image with Javascript

A QR code is short and sweet (besides quite useful) for a quick response (they can be read quickly by a smartphone). Yep, they're normally scanned by someone with a smartphone ,but thanks to jsqrcode, we can achieve the scanning process without a camera and decode the information from plain (PNG or JPEG) images (in base64 format to be more specific and to increase accuracy) in case you ever need such a feature in any of your crazy company (or own) projects.

In this article, you'll learn how to scan a QR Code from its base64 value easily using jsqrcode.

Requirements

To achieve our goal, we are going to depend on the jsqrcode library. This library is a JavaScript QRCode reader implementation for HTML5 created by Lazar Laszlo. You can download (or clone) its source code in the official repository in Github here. The source code itself is based in 17 different JS files (that needs obviously to be loaded in your html document using the script tag).

Implementation

Basically, to use the library you'll need to use 2 lines, set a callback that receives the decoded data and provide the base64 image as first parameter in the decode function:

// set the callback that receives the decoded content as the tasks is async
qrcode.callback = function(decodedDATA){
      alert(decodedDATA);
};

// Start decoding the base64 string
qrcode.decode("data:image/png;.......");

The following snippet, shows the most basic usage in a simple html snippet (feel free to download and test it locally). The imageURI variable contains a QRCode image (in this case PNG but it can be JPG) in base64 and it will be given as first parameter in our custom function decodeImageFromBase64.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Decode QRCode from image using javascript</title>
    </head>
    <body>
        <input type="button" id="action" value="Decode"/>
        <script type="text/javascript" src="grid.js"></script>
        <script type="text/javascript" src="version.js"></script>
        <script type="text/javascript" src="detector.js"></script>
        <script type="text/javascript" src="formatinf.js"></script>
        <script type="text/javascript" src="errorlevel.js"></script>
        <script type="text/javascript" src="bitmat.js"></script>
        <script type="text/javascript" src="datablock.js"></script>
        <script type="text/javascript" src="bmparser.js"></script>
        <script type="text/javascript" src="datamask.js"></script>
        <script type="text/javascript" src="rsdecoder.js"></script>
        <script type="text/javascript" src="gf256poly.js"></script>
        <script type="text/javascript" src="gf256.js"></script>
        <script type="text/javascript" src="decoder.js"></script>
        <script type="text/javascript" src="qrcode.js"></script>
        <script type="text/javascript" src="findpat.js"></script>
        <script type="text/javascript" src="alignpat.js"></script>
        <script type="text/javascript" src="databr.js"></script>
        <script>
            // A qrcode with "ourcodeworld.com" as value in format base64 encoded
            var imageURI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASIAAAEiAQMAAABncE31AAAABlBMVEX///8AAABVwtN+AAABA0lEQVRoge3ZUQ6CMAzG8SYcwCNx9R2JA5jU0a6ARKIP60z0/z0wZD+fmm1siBBCCPmfaMu93t/sEk8KKlv5jwrq3VT7jO4dqEy1lsT65mVS92vBUAOVKupbKmYm1DhljffpB/MXqp/aVmQfIuXNuo3qp46p4KIHlaFiTKzXRdrS4GszKlnJHCPBhkgF2z9RyWqvkNWlUdWrOqL6qZiP2kuoVWivGipT+cAosfsNOqHy1cm34txOuwBUhtKW2Hf52Zu8XLdRnVWxZtt3+duQ3gU1QD2d+kSFBDVUFX8ytZcj1Eh1OHMWQQ1Q1kSF2hb4ev5CdVTHFVl1/86FSleEEEJ+PQ/ANYzwx13NHQAAAABJRU5ErkJggg==";

            /**
             * The function decodeImageFromBase64 expects as first parameter a base64 string from a QRCode.
             * As second parameter the callback that expects the data from the QRCode as first parameter.
             */
            function decodeImageFromBase64(data, callback){
                // set callback
                qrcode.callback = callback;
                // Start decoding
                qrcode.decode(data)
            }

            // On button click, decode the qrCode from the base64 format.
            document.getElementById("action").addEventListener('click',function(){
                decodeImageFromBase64(imageURI,function(decodedInformation){
                    alert(decodedInformation);
                });
            },false);
        </script>
    </body>
</html>

Is up to you how to convert an image (whatever the source is i.e your own website from an url or a local file) into its base64 format to be processed by the jsqrcode library.

Note that you get to work this scanner code with the getUserMedia API in order to create a live QR Code scanner with your webcamera, however that's another story and you can see a working example in the official demo website of the library.

Have fun !

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...