Use Goolge Open Source Tool zxing implement QR code reading and Writing tool (with logo)

Source: Internet
Author: User
Tags border color flush
Tool class: Qrcodecreateutil.java
Package org.zwc.zxingtest;
Import java.awt.*;
Import Java.awt.image.BufferedImage;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;

Import java.util.Hashtable;

Import Javax.imageio.ImageIO;
Import Com.google.zxing.BarcodeFormat;
Import Com.google.zxing.BinaryBitmap;
Import Com.google.zxing.EncodeHintType;
Import Com.google.zxing.LuminanceSource;
Import com.google.zxing.ReaderException;
Import Com.google.zxing.Result;
Import com.google.zxing.WriterException;
Import Com.google.zxing.client.j2se.BufferedImageLuminanceSource;
Import Com.google.zxing.common.BitMatrix;
Import Com.google.zxing.common.HybridBinarizer;
Import Com.google.zxing.qrcode.QRCodeReader;
Import Com.google.zxing.qrcode.QRCodeWriter;

Import Com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
 /** * Created by Zhangwenchao on 2017/11/24. */public class Qrcodecreateutil {/** * generates include charactersString information Two-dimensional code picture----without logo, go to white box * * @param outputstream file output stream path * @param content QR code carrying information * @param qrcodes ize QR code image size * @param imageformat QR code format * @throws writerexception * @throws IOException */Publ IC Static Boolean Createqrcode (OutputStream outputstream, String content, int qrcod Esize, String imageformat) throws Writerexception, IOException {//Set two-dimensional code error correction level map hashtable<
        Encodehinttype, errorcorrectionlevel> hintmap = new Hashtable<encodehinttype, errorcorrectionlevel> ();

        Malocclusion level Hintmap.put (encodehinttype.error_correction, ERRORCORRECTIONLEVEL.L);

        New Qrcodewriter Qrcodewriter qrcodewriter = new Qrcodewriter (); Create a bit matrix (bit matrix) QR Code encoded string Bitmatrix Bytematrix = Qrcodewriter.encode (content, Barcodeformat.qr_code, Qrcodesize, QrC
        Odesize, Hintmap); Make BufferedImage sketch QRCode (Matrixwidth is the line two-dimensional code pixel point) int matrIxwidth = Bytematrix.getwidth (); Create a new memory cache picture----picture size is qrCodeSize-200 (note: Bytematrix will have some white border, depending on the size of the resulting picture, the white border size is different) bufferedimage image = New Bufferedim
        Age (matrixWidth-200, matrixWidth-200, Bufferedimage.type_int_rgb);
        Graphics2D graphics = Image.creategraphics ();
        Graphics2D graphics = (graphics2d) image.getgraphics ();
        Graphics.setcolor (Color.White); Graphics.fillrect (0, 0, matrixwidth, matrixwidth);
        Fill white on the image//use the bit matrix to draw and save the image Graphics.setcolor (Color.Black); for (int i = 0, i < matrixwidth; i++) {for (int j = 0; J < Matrixwidth; J + +) {if (byte
                Matrix.get (i, J)) {//Remove Border Graphics.fillrect (i-100, j-100, 1, 1);//Draw a black pixel
    }}} return Imageio.write (image, ImageFormat, outputstream);
 /** * Generate a QR code image containing string information----with logo * Add logo is actually two pictures overlay * * @param outputstream file output stream path    * @param content QR code carry information * @param qrcodesize QR code image size * @param imageformat QR code format * @throws writ Erexception * @throws IOException */public static Boolean Createqrcodewithlogo (OutputStream outputstream, S Tring content, int qrcodesize, String imageformat,string logoimage) thr oWS writerexception, IOException {//Set two-dimensional code error correction level map Hashtable<encodehinttype, errorcorrectionlevel> H
        Intmap = new Hashtable<encodehinttype, errorcorrectionlevel> ();

        Malocclusion level Hintmap.put (encodehinttype.error_correction, ERRORCORRECTIONLEVEL.L);

        New Qrcodewriter Qrcodewriter qrcodewriter = new Qrcodewriter (); Create a bit matrix (bit matrix) QR Code encoded string Bitmatrix Bytematrix = Qrcodewriter.encode (content, Barcodeformat.qr_code, Qrcodesize, QrC
        Odesize, Hintmap);
        Make BufferedImage sketch QRCode (Matrixwidth is the line two-dimensional code pixel) int matrixwidth = Bytematrix.getwidth (); //Create a new memory cache picture----picture size is qrCodeSize-200 (note: Bytematrix will have some white border, depending on the size of the resulting picture, the white border size is different) bufferedimage image = New Bufferedima
        GE (matrixWidth-200, matrixWidth-200, Bufferedimage.type_int_rgb);
        Graphics2D graphics = Image.creategraphics ();
        Graphics2D graphics = (graphics2d) image.getgraphics ();
        Graphics.setcolor (Color.White); Graphics.fillrect (0, 0, matrixwidth, matrixwidth);
        Fill white on the image//use the bit matrix to draw and save the image Graphics.setcolor (Color.Black); for (int i = 0, i < matrixwidth; i++) {for (int j = 0; J < Matrixwidth; J + +) {if (byte
                Matrix.get (i, J)) {//Remove Border Graphics.fillrect (i-100, j-100, 1, 1);//Draw a black pixel  }}}/** * z */File Logopic = new file (logoimage);
               Logo document if (!logopic.isfile ()) {System.out.print ("logo file is not find!");
       System.exit (0); } bufferedimage logobufferedimage = Imageio.read (logopic); Read logo image/** * Re-set the size of the logo, set to 20% of the QR code picture, because the assembly to cover the two-dimensional code */int Widthlogo = Logobufferedi Mage.getwidth (NULL) >image.getwidth () *2/10?
         (Image.getwidth () *2/10): Logobufferedimage.getwidth (NULL); int Heightlogo = Logobufferedimage.getheight (null) >image.getheight () *2/10?


        (Image.getheight () *2/10): Logobufferedimage.getheight (NULL);
        Calculate the location of the logo image placement---logo placed in center int x = (Image.getwidth ()-Widthlogo)/2;



        int y = (image.getheight ()-Heightlogo)/2;
        Start drawing logo to QR code image on Graphics.DrawImage (logobufferedimage, x, Y, Widthlogo, Heightlogo, NULL);
        Graphics.drawroundrect (x, Y, Widthlogo, Heightlogo, 15, 15);  Graphics.setstroke (New Basicstroke (2)); Border Graphics.setcolor (Color.green);

        Border color Graphics.drawrect (x, Y, Widthlogo, Heightlogo);
        Graphics.dispose ();
        Logobufferedimage.flush (); ImaGe.flush ();
    return Imageio.write (image, ImageFormat, outputstream);
        }/** * Read the QR code and output the information carried * * * public static void Readqrcode (InputStream inputstream) throws IOException {

        Gets the string information from the input stream bufferedimage image = Imageio.read (InputStream);
        Convert an image to a bits luminancesource Source = new Bufferedimageluminancesource (image);

        Binarybitmap bitmap = new Binarybitmap (new Hybridbinarizer (source));  Qrcodereader reader = new Qrcodereader ();
        result = NULL;
        try {result = Reader.decode (bitmap);
        } catch (Readerexception e) {e.printstacktrace ();
    } System.out.println (Result.gettext ()); /** * Test Code * @throws writerexception */public static void main (string[] args) throws Ioexceptio N, writerexception {createqrcode (New FileOutputStream ("E:\\qrcode.jpg"), "We8sasdfdfsdsdf12sdfe3", 800
        , "JPEG"); creatEqrcodewithlogo (New FileOutputStream ("E:\\qrcodewithlogo.jpg"), "We8sasdfdfsdsdf12sdfe3", "+", "JPEG", "E

        : \\ling.jpg ");
        Readqrcode (New FileInputStream ("e:\\qrcode.jpg"));
    Readqrcode (New FileInputStream ("e:\\qrcodewithlogo.jpg"));
 }

}

Test results:
Generate two-dimensional code (with logo):
Read Result:
We8sasdfdfsdsdf12sdfe3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.