Using zxing to generate a two-dimensional code picture with logo, automatically adjust the logo picture relative to the size of the two-dimensional code picture __java

Source: Internet
Author: User
Tags base64 border color
Use zxing to generate a two-dimensional code picture with logo, automatically adjust the size of the logo picture relative to the two-dimensional code picture
* Optional whether with logo, choose whether to save two-dimensional code picture; result returns a base64 encoded picture data string
* Page display:
* Maven Jar
* <dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.1.0</version>

</dependency>

Two-dimensional code generation tool class download: Click to open the link

Original author http://www.kancloud.cn/digest/javaxviii/126763

I'll get it myself.


1. Two-dimension code with logo


2. Two-dimensional code without logo


3. The list directly reads the two-dimensional code base64 encoded string stored in the database, displayed to the page



Tool class, you can customize the implementation of the resulting picture size, etc.:

Package com.niuhuohuo.assets.utils;
Import Java.awt.Color;
Import Java.awt.Font;
Import Java.awt.Graphics2D;
Import Java.awt.image.BufferedImage;
Import Java.io.ByteArrayOutputStream;
Import Java.io.File;
Import Java.util.Date;
Import Java.util.HashMap;

Import Java.util.Map;

Import Javax.imageio.ImageIO;

Import org.apache.commons.codec.binary.Base64;
Import Com.google.zxing.BarcodeFormat;
Import Com.google.zxing.EncodeHintType;
Import Com.google.zxing.MultiFormatWriter;
Import com.google.zxing.WriterException;
Import Com.google.zxing.common.BitMatrix;

Import Com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; /** * Use zxing to generate a two-dimensional code picture with a logo, automatically adjust the logo picture relative to the size of two-dimensional code picture * Optional logo, whether or not to save two-dimensional code picture; results returns the base64 encoded picture data String * page display:  * maven jar * <dependency> <groupid>com.google.zxing</g
 roupid> <artifactId>core</artifactId> <version>3.1.0</version> </dependency> * @author NHHyx * @date 20170314 */public class Zxingcodeutils {private static final int qrcolor = 0xff000000;   The default is black private static final int bgwhite = 0xFFFFFFFF; Background color public static void main (string[] args) throws Writerexception {try {* * Call Sample 1, from the project to obtain the logo picture, the resulting two-dimensional code picture is also saved to the project designated folder, using MyEclipse, and so on, the resulting two-dimensional code picture in the tomcat/webapps/project///Generate two-dimensional code picture and base64 Code data is updated to the database, data:image/png;base64,***//logo picture/*string Logourl = Request.getsession (). Getservletcontext (). Get
		    Realpath ("/web-inf/assets/admin/img/temp/logo.png");
        	File Logofile = new file (Logourl); 
        	Output two-dimensional code path String Outpath = Request.getsession (). Getservletcontext (). Getrealpath ("/web-inf/assets/qr"); String base64img = Zxingcodeutils.createqrcode (Logofile, "This is the contents of the two-dimensional code, can be HTTP URL", Outpath, 400, 400, "this is a two-dimensional code picture under the text, with the image generated "); * * Call the Sample 2/*//string FilePath = request.getsession (). GetservletconteXT (). Getrealpath ("/") + "resources/images/logoimages/llhlogo.png"; /* Logo picture path and two-dimensional code output path String Logourl = Request.getsession (). Getservletcontext (). Getrealpath ("/web-inf/assets/
        	Admin/img/temp/logo.png "); String Outpath = Request.getsession (). Getservletcontext (). Getrealpath ("/WEB-INF/ASSETS/QR"); * *//filepath is two
        	Dimension Code logo path, but in practice we are placed under a certain path of the project, so the path with the above, the following note is good String Logopath = "C:\\logo.png";
        	File Logofile = new file (Logopath);
        	String Outpath = "C:";
        Createqrcode (Logofile, "2asdf5", Outpath, 400, 400, "This is the two-dimensional code under the text");  
        catch (Exception e) {e.printstacktrace (); /** * Generate a two-dimensional code picture with a logo * @param logopath two-dimensional code picture contains the logo picture file, if not, then generate a two-dimensional code without a logo picture * @param co Ntent content or Jump path * @param outpath two-dimensional code output path, if "" will not output the picture to the specified position, only return base64 picture String * @param qrimgwidth two-dimensional code picture width * @par Am Qrimgheight Two-dimensional code picture height (with text will be heightened 45px) * @param productnAme the text under the two-dimensional code picture * @return/public static string Createqrcode (File logofile, string content, String Outpath,  int qrimgwidth, int qrimgheight, String productName) {try {zxingcodeutils ZP = new
        	Zxingcodeutils (); Generate a two-dimensional code bufferedimage picture BufferedImage BIM = zp.getqrcodebufferedimage (content, Barcodeformat.qr_code, Qrimgwid
            
            Th, Qrimgheight, Zp.getdecodehinttype ()); If there is text, the two-dimensional code picture height increases by 45px if (! "").
        	Equals (ProductName)) {qrimgheight = 45; //To add a logo to the two-dimensional code picture and save it to the specified location, return the base64 encoded picture data string returned Zp.createlogoqrcode (Outpath, Qrimgwidth, qrimg
        Height, Bim, Logofile, New Logoconfig (), productName);
        catch (Exception e) {e.printstacktrace ();
    return null; /** * To add logo image to two-dimensional code picture and generate final two-dimensional code picture * @param outpath output two-dimensional code picture path, if "" is not output picture to the specified location, only return base64 picture String * @para M qrimgwidth to generate two-dimensional codePicture Width * @param qrimgheight generate two-dimensional code picture Height * @param bim read two-dimensional code picture bufferedimage Object * @param logopic logo picture file * @param logoconfig Logo configuration * @param productName the text under the two-dimensional code picture * @return Returns the encoded string of the picture base64/public Strin G Createlogoqrcode (String outpath, int qrimgwidth, int qrimgheight, BufferedImage Bim, File logopic, Logoconfig logoconfig
            , String productName) {try {/** * reads a two-dimensional code picture and constructs a drawing object * *
            
            BufferedImage image = Bim; If the logo picture exists, add it to the two-dimensional code picture if (logopic!= null && logopic.exists ()) {graphics2d g = image.cr
	
	            Eategraphics ();
	            /** * Read logo picture * * BufferedImage logo = Imageio.read (logopic); /** * Set the size of the logo, I set the two-dimensional code picture of 20%, because the General Assembly to cover up the two-dimensional code */int widthlogo = Logo.getwidth (null) & Gt;image.getwidth () *3/10? (Image.getwidth () *3/10): Logo.getwidth (nulL), Heightlogo = Logo.getheight (null) >image.getheight () *3/10?
	
	            (Image.getheight () *3/10): Logo.getwidth (NULL);
	             /** * logo is placed in center * * * int x = (Image.getwidth ()-Widthlogo)/2;
	             int y = (image.getheight ()-Heightlogo)/2;
	             /** * logo in the lower right corner * int x = (Image.getwidth ()-Widthlogo);
	             * Int y = (image.getheight ()-Heightlogo);
//Start drawing picture g.drawimage (logo, x, y, Widthlogo, Heightlogo, NULL);
G.drawroundrect (x, Y, Widthlogo, Heightlogo, 15, 15);
G.setstroke (New Basicstroke (Logoconfig.getborder ()));
G.setcolor (Logoconfig.getbordercolor ());
            	G.drawrect (x, Y, Widthlogo, Heightlogo);
            	
            	G.dispose ();
            Logo.flush (); //Add the name of the product, the name of the product should not be too long, here support two lines. Too long will automatically intercept if (ProductName!= null &AMP;&AMP,!productname.equals ("")) {//new picture, add text underneath the two-dimensional code with logo bufferedimage outimage = new Buffer
                Edimage (Qrimgwidth, Qrimgheight, BUFFEREDIMAGE.TYPE_4BYTE_ABGR);
                Graphics2D OUTG = Outimage.creategraphics ();
                Draw the two-dimensional code to the new panel outg.drawimage (image, 0, 0, image.getwidth (), image.getheight (), NULL); 
                Draw the text to the new panel Outg.setcolor (Color.Black); Outg.setfont (New Font ("Song Body", Font.Bold, 26));
                Font, typeface, font size int strwidth = Outg.getfontmetrics (). Stringwidth (ProductName); if (Strwidth > 399) {////length is too long to intercept the front part//outg.drawstring (productName, 0, Image.gethe Ight () + (Outimage.getheight ()-image.getheight ())/2 + 5); Draw text//length too long to wrap String productName1 = productname.substring (0, Productname.length (
                    )/2); String productName2 = productname.substring (Productname.length ()/2, Productname.length ());
                    int strWidth1 = Outg.getfontmetrics (). Stringwidth (PRODUCTNAME1);
                    int strWidth2 = Outg.getfontmetrics (). Stringwidth (productName2); 
                    Outg.drawstring (productName1, 200-STRWIDTH1/2, Image.getheight () + (Outimage.getheight ()-image.getheight ())/2 + 12);
                    BufferedImage outImage2 = new BufferedImage (485, BUFFEREDIMAGE.TYPE_4BYTE_ABGR);
                    Graphics2D OUTG2 = Outimage2.creategraphics ();
                    Outg2.drawimage (outimage, 0, 0, outimage.getwidth (), outimage.getheight (), NULL); 
                    Outg2.setcolor (Color.Black); Outg2.setfont (New Font ("Song Body", Font.Bold, 26)); fonts, font, font size outg2.drawstring (productName2, 200-STRWIDTH2/2, Outimage.getheight () + (outimage2.gethe
                    Ight ()-outimage.getheight ())/2 + 5); 
                    Outg2.dispose ();
                    Outimage2.flush (); Outimage = OUtImage2; }else {outg.drawstring (ProductName, 200-STRWIDTH/2, Image.getheight () + (Outimage.getheight ()-I Mage.getheight ())/2 + 12); 
                Draw text} outg.dispose ();
                Outimage.flush ();
            image = Outimage;
            }//logo.flush ();
            Image.flush ();
            Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
            Baos.flush ();

            Imageio.write (Image, "png", BAOs); If the output path is empty, the two-dimensional code picture is not saved under the specified path if (!). Equals (Outpath.trim ())) {//two D-code generated path, but in the actual project, we are showing the generated two-dimensional code to the interface, so the following line of code can be commented out///You can see that this method eventually returns the Two-dimensional code IMAGEBASE64 string//front End with  Where ${imagebase64qrcode}   
            ImageBase64 string Imageio.write (image, "PNG", new File (Outpath + "\" + New Date (), getTime () + ". png") for the two-dimensional code; //Get Base64 encoded two-dimensional code pictureString imagebase64qrcode = Base64.encodebase64string (Baos.tobytearray ());
            Baos.close ();
        return imagebase64qrcode;
        catch (Exception e) {e.printstacktrace ();
    return null; /** * Build Initialization two-dimensional code * * @param BM * @return/public bufferedimage filetobufferedimage (Bit
        Matrix BM) {bufferedimage image = null;
            try {int w = bm.getwidth (), H = bm.getheight ();

            Image = New BufferedImage (W, H, Bufferedimage.type_int_rgb);
                    for (int x = 0; x < W x + +) {for (int y = 0; y < h; y++) {
                Image.setrgb (x, Y, Bm.get (x, y)? 0xff000000:0xffccddee);
        A catch (Exception e) {e.printstacktrace ());
    } return image; /** * Generate a two-dimensional code bufferedimage picture * * @param content * Encoded CONTENTS * @param barcodeformat * Encoding type * @param width *
    Picture Width * @param height * Picture Heights * @param hints * Set parameters * @return * * Public bufferedimage getqrcodebufferedimage (String content, Barcodeformat barcodeformat, int width, int height, map<
        Encodehinttype,?> hints) {multiformatwriter multiformatwriter = null;
        Bitmatrix BM = NULL;
        BufferedImage image = null;
            try {multiformatwriter = new multiformatwriter (); The parameter order is: encoding content, encoding type, generating picture width, generating picture height, setting parameters BM = Multiformatwriter.encode (content, Barcodeformat, width, height, h
            INTs);
            int w = bm.getwidth ();
            int h = bm.getheight ();

            Image = New BufferedImage (W, H, Bufferedimage.type_int_rgb);
      Start using two-dimensional code data to create bitmap pictures, respectively, set to Black (0xFFFFFFFF) White (0xff000000) for (int x = 0; x < W x + +)      {for (int y = 0; y < h; y++) {Image.setrgb (x, Y, Bm.get x, Y)?
                Qrcolor:bgwhite);
        A catch (Writerexception e) {e.printstacktrace ());
    } return image; /** * Set the format parameter of the two-dimensional code * * @return/public Map<encodehinttype, Object> Getdecodehinttype ( {///used to set QR two-dimensional code parameter Map<encodehinttype, object> hints = new Hashmap<encodehinttype, object>
        ();
        Set the error-correcting level (H is the highest level) for QR two-dimensional code hints.put (encodehinttype.error_correction, ErrorCorrectionLevel.H);
        Set encoding mode Hints.put (Encodehinttype.character_set, "utf-8");
        Hints.put (encodehinttype.margin, 0);
        Hints.put (Encodehinttype.max_size, 350);

        Hints.put (encodehinttype.min_size, 100);
    return hints; }/** * Logo configuration * @author Nhhyx * */class Logoconfig {//logo default border color PubliC static final Color Default_bordercolor = Color.White;
    Logo default border width public static final int default_border = 2;

    The logo size defaults to the photo's 1/5 public static final int default_logopart = 5;
    Private final int border = Default_border;
    Private final Color bordercolor;

    private final int logopart; /** * Creates a default Config with in color {@link #BLACK} and off color * {@link #WHITE}, generating normal bl
     Ack-on-white Barcodes.
    * * Public logoconfig () {This (Default_bordercolor, Default_logopart);
        Public Logoconfig (Color bordercolor, int logopart) {this.bordercolor = bordercolor;
    This.logopart = Logopart;
    Public Color Getbordercolor () {return bordercolor;
    public int Getborder () {return border;
    public int Getlogopart () {return logopart;
 }
}


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.