How to generate and read QR code with Java using ZXing Library

QRCode is abbreviated as Quic Response Code and we are quite familiar with QRCodes now a days. It is used for authenticated and quick online payments. A QR code uses four standardized encoding modes (numeric, alphanumeric, byte/binary, and kanji) to store data efficiently; extensions may also be used.

A QRCode is an arrangement of black and white squares and can be read with various QRCode Scanners and is convenient today because every smartphone has a QRcode scanner app.



Library used for generating QRCodes (ZXing)

ZXing (“Zebra Crossing”) is the popular API for QR code processing in Java. Its library has multiple components and we will be using the ‘core’ for QR code creation in our Java example.

How to generate QR code?


Following code is an example to create a QR code image.

  1. Download the ZXING library from here.
  2. Add ZXING dependency in maven file.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <dependencies>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.3.0</version>
        </dependency>
    </dependencies>    

    chevron_right

    
    

  3. Write the code to generate QR code and save it as a jpg file in the native folder.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java code to generate QR code
      
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
      
    import javax.imageio.ImageIO;
      
    import com.google.zxing.BarcodeFormat;
    import com.google.zxing.BinaryBitmap;
    import com.google.zxing.EncodeHintType;
    import com.google.zxing.MultiFormatReader;
    import com.google.zxing.MultiFormatWriter;
    import com.google.zxing.NotFoundException;
    import com.google.zxing.Result;
    import com.google.zxing.WriterException;
    import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
    import com.google.zxing.client.j2se.MatrixToImageWriter;
    import com.google.zxing.common.BitMatrix;
    import com.google.zxing.common.HybridBinarizer;
    import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
      
    public class QRCode {
      
        public static void main(String[] args)
            throws WriterException,
                   IOException,
                   NotFoundException
        {
      
            // The data that the QR code will contain
            String data = "www.geeksforgeeks.org";
      
            // The path where the image will get saved
            String path = "F:\user\QRCodes";
      
            // Encoding charset
            String charset = "UTF-8";
      
            Map<EncodeHintType,
                ErrorCorrectionLevel>
                hashMap
                = new HashMap<EncodeHintType,
                              ErrorCorrectionLevel>();
      
            hintMap.put(
                EncodeHintType.ERROR_CORRECTION,
                ErrorCorrectionLevel.L);
      
            // Create the QR code and save
            // in the specified folder
            // as a jpg file
            createQRCode(fileName, path,
                         charset, hashMap,
                         200, 200);
            System.out.println(
                "QR Code Generated!!! ");
        }
      
        // Function to create the QR code
        public static void createQR(
            String data, String path,
            String charset, Map hashMap,
            int height, int width)
            throws WriterException, IOException
        {
      
            BitMatrix matrix
                = new MultiFormatWriter().encode(
                    new String(
                        qrCodeData.getBytes(charset),
                        charset),
                    BarcodeFormat.QR_CODE, width, height);
      
            MatrixToImageWriter
                .writeToFile(
                    matrix,
                    path.substring(
                        path.lastIndexOf('.') + 1),
                    new File(path));
        }
    }

    chevron_right

    
    

  4. Output file will be by name gog.jpg

  5. On scanning this QRCode you will be redirected to geeksforgeeks home page.

How to generate QR code?


After generating QR code, we can also read the QR code image file using ZXing library. Below is the code to do so.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to read the QR code
  
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
  
import javax.imageio.ImageIO;
  
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
  
public class QRCode {
  
    public static void main(String[] args)
        throws WriterException,
               IOException,
               NotFoundException
    {
  
        // Path where the QR code is saved
        String path = "F:\user\QRCodes";
  
        // Encoding charset
        String charset = "UTF-8";
  
        Map<EncodeHintType,
            ErrorCorrectionLevel>
            hashMap
            = new HashMap<EncodeHintType,
                          ErrorCorrectionLevel>();
  
        hintMap.put(
            EncodeHintType.ERROR_CORRECTION,
            ErrorCorrectionLevel.L);
  
        System.out.println(
            "QRCode output: "
            + readQRCode(filePath,
                         charset,
                         hintMap));
    }
  
    // Function to read the QR file
    public static String readQR(
        String path,
        String charset,
        Map hashMap)
        throws FileNotFoundException,
               IOException,
               NotFoundException
    {
        BinaryBitmap binaryBitmap
            = new BinaryBitmap(
                new HybridBinarizer(
                    new BufferedImageLuminanceSource(
                        ImageIO.read(
                            new FileInputStream(path)))));
  
        Result result
            = new MultiFormatReader()
                  .decode(binaryBitmap);
  
        return result.getText();
    }
}

chevron_right


Output:

QRCode output: www.geeksforgeeks.org



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.