Generate two-dimensional code picture in Java __java

Source: Internet
Author: User
Tags parse error log4j
Java generation two-dimensional code picture

There are several ways to generate two-dimensional code images in Java, such as Google's Zxing Toolkit and Swetakeqrcode Toolkit.
The following uses the Swetakeqrcode toolkit to generate a two-dimensional code picture sample:
Pom File introduces Swetakeqrcode toolkit dependencies:

<!--two-dimensional code generation tool jar Package-->
<dependency>
    <groupId>com.swetake.util</groupId>
    < artifactid>qrcode</artifactid>
    <version>1.0</version>
</dependency>

Qrcodeimageutil Tool Class Code:

* * Filename Qrcodeimageutil.java * Company XXX Information Technology Co., Ltd.

* @author Leo * @version 3.4.0 * * Package com.leo.common.imageutil;
Import Java.awt.Color;
Import Java.awt.Graphics2D;
Import Java.awt.Image;
Import Java.awt.image.BufferedImage;
Import Java.io.File;

Import Java.io.OutputStream;

Import Javax.imageio.ImageIO;
Import Org.apache.log4j.Logger;

Import Org.springframework.data.redis.connection.DataType;
Import Com.swetake.util.Qrcode;
Import Com.leo.common.cache.RedisCacheManager;
Import Com.leo.common.platform.PJectPathUtil;

Import Com.leo.common.platform.config.ConfigResource;  /** * Two-dimensional code generation tool class * * @author Leo * @since 3.4.0_2016 year June 29 * * Public class Qrcodeimageutil {private static Logger

    Logger = Logger.getlogger (Qrcodeimageutil.class);

    private static final String Imagesavepath = Configresource.getconfig (). GetProperty ("Image.save.path");

    private static final String Imagevisitpath = Configresource.getconfig (). GetProperty ("Image.visit.path"); PrivaTe static final Rediscachemanager manager = Rediscachemanager.getinstance ();

    public static final String two_code_img_key_name = "Two_code_img_"; /** * Generate two-dimensional code (QRCODE) picture (with logo)--Output to file * @param content two-dimensional code picture contents * @param imgpath generate a two-dimensional code picture complete path * param Logopath Two-dimensional code picture in the middle of the logo path * @param version two-dimensional code versions, a value range of 1-40, the larger the value of the larger size, the greater the information can be stored * @return 0: Said success-1: To express the content of the incoming ask Question-100: Generates an exception * @author Leo * @since 3.4.0_2016 year June 29 * * public static int Createqrcode (String Co
               Ntent, String imgpath,string logopath,int version) {try {qrcode Qrcodehandler = new QRCode (); Set the two-dimensional code error rate, optional L (7%), M (15%), Q (25%), H (30%), the higher the rate of error, the less information can be stored, but the requirements of two-dimensional code clarity Qrcodehandler.setqrcodee
               Rrorcorrect (' M ');
               n represents a number, and a represents a character a-z,b representing other characters qrcodehandler.setqrcodeencodemode (' B ');
            Set up a two-dimensional code version, take a value range of 1-40, the larger the value of the larger size, the more information can be stored qrcodehandler.setqrcodeversion (version);   Picture size int imgsize =67 + (version-1);
               byte[] Contentbytes = content.getbytes ("UTF-8");
               BufferedImage image = New BufferedImage (imgsize, imgsize, Bufferedimage.type_int_rgb);

               graphics2d GS = Image.creategraphics ();
               Gs.setbackground (Color.White);

               Gs.clearrect (0, 0, imgsize, imgsize);

               Set Image Color > Black gs.setcolor (Color.Black);
               Setting offset without setting may cause parsing error int pixoff = 2;
                   Output > Two-dimensional code if (Contentbytes.length > 0 && contentbytes.length < 130) {
                   boolean[][] Codeout = Qrcodehandler.calqrcode (contentbytes);
                           for (int i = 0; i < codeout.length. i++) {for (int j = 0; J < Codeout.length; J +) { 
  if (Codeout[j][i]) {Gs.fillrect (J * 3 + Pixoff, I * 3 + Pixoff, 3, 3);                         else {Logger}}}}
                   . info ("qrcode content bytes Length =" + Contentbytes.length + "not in [0,125].");
               return-1;
               Image logo = Imageio.read (new File (Logopath));//Instantiate an Image object. int Widthlogo = Logo.getwidth (null) >image.getwidth () *2/10?
               (Image.getwidth () *2/10): Logo.getwidth (NULL); int Heightlogo = Logo.getheight (null) >image.getheight () *2/10?

                (Image.getheight () *2/10): Logo.getwidth (NULL);
               /** * logo is placed in center * * * int x = (Image.getwidth ()-Widthlogo)/2;
               int y = (image.getheight ()-Heightlogo)/2;
               Gs.drawimage (logo, x, y, Widthlogo, Heightlogo, NULL);
               Gs.dispose ();

               Image.flush ();
               Generate a two-dimensional code qrcode picture File Imgfile = new file (Imgpath); ImageiO.write (Image, "png", imgfile);
               catch (Exception e) {logger.error ("Generate two-dimensional code picture exception:" + E);
           return-100;
       return 0; /** * * Generate two-dimensional code picture (without logo)-Output to stream * * @param content two-dimensional code picture contents * @param wi DTH two-dimensional code picture of the width * @param height two-dimensional code picture High * @param os two-dimensional code output stream * @author Leo * @since 3.4.0_2016 year
            June 29 */public static void Encoderqrcoder (String content, int width, int height, outputstream os) {
                try {QRCode handler = new QRCode ();
                Set up the error-correcting ability of the two-dimensional code//l 7% m 15% Q 25% H 30% handler.setqrcodeerrorcorrect (' M ');
                Storage of Handler.setqrcodeencodemode (' B ') in binary form;

                Set up a two-dimensional code version of 1=21*21 2=25*25 handler.setqrcodeversion (7);
                byte[] Contentbytes = content.getbytes ("UTF-8"); Byte[] Contentbytes = new String (content.getbytes ("iso-8859-1"), "UTF-8"). GetBytes ();; 
                Create a buffer for image data (create a sheet of paper) BufferedImage bufimg = new BufferedImage (width, height, bufferedimage.type_int_rgb);
                Create a pen graphics2d GS = Bufimg.creategraphics ();
                Set the background color to white gs.setbackground (color.white);

                Fill the paper up gs.clearrect (0, 0, width, height);

                Set Image color: Black Gs.setcolor (Color.Black);
                Set offset not set Ken can cause parse error int pixoff = 2; Output: Two-dimensional code if (Contentbytes.length > 0 && contentbytes.length < 124) {Bo
                    olean[][] Codeout = Handler.calqrcode (contentbytes);
                            for (int i = 0; i < codeout.length. i++) {for (int j = 0; J < Codeout.length; J +) { if (Codeout[j][i]) {//drawing from a Boolean arrayThe two-dimensional code rectangle diagram Gs.fillrect (J * 3 + Pixoff, I * 3 + pixoff,3, 3);  else {logger.info ("QRCode content

                Bytes length = "+ Contentbytes.length +" not in [0,125]. ");}
                Gs.dispose ();

                Bufimg.flush ();

            Generate two-dimensional Code qrcode picture Imageio.write (bufimg, "PNG", OS);
            catch (Exception e) {logger.error ("Generate two-dimensional code picture exception:" + E); /** * * Generate two-dimensional code picture (without logo)--output to file--add Redis * * @param content two-dimensional code map 
        The content of the film * @param width two-dimensional code picture of the width * @param height two-dimensional code picture of the high * @param key logo redis key * @author Leo * @since 3.4.0_2016 Year June 29/* public static string Get2coderinfile (String content, int width, int h
           Eight, string key) {string imgpath = ""; Try {QRCode handler = new QRCode ();
               Set up the error-correcting ability of the two-dimensional code//l 7% m 15% Q 25% H 30% handler.setqrcodeerrorcorrect (' M ');
               Storage of Handler.setqrcodeencodemode (' B ') in binary form;

               Set up a two-dimensional code version of 1=21*21 2=25*25 handler.setqrcodeversion (7);
               byte[] Contentbytes = content.getbytes ("UTF-8");
               byte[] contentbytes = new String (content.getbytes ("iso-8859-1"), "UTF-8"). GetBytes ();;
               Create a buffer for image data (create a sheet of paper) BufferedImage bufimg = new BufferedImage (width, height, bufferedimage.type_int_rgb);
               Create a pen graphics2d GS = Bufimg.creategraphics ();
               Set the background color to white gs.setbackground (color.white);

               Fill the paper up gs.clearrect (0, 0, width, height);

               Set Image color: Black Gs.setcolor (Color.Black); Set offset not set Ken can cause parse error int pixoff =2; Output: Two-dimensional code if (Contentbytes.length > 0 && contentbytes.length < 124) {bool
                   ean[][] Codeout = Handler.calqrcode (contentbytes);
                           for (int i = 0; i < codeout.length. i++) {for (int j = 0; J < Codeout.length; J +) { if (Codeout[j][i]) {//two-dimensional code rectangle drawing based on a Boolean array gs.f
                           Illrect (J * 3 + Pixoff, I * 3 + pixoff,3, 3); else {logger.info ("QRCode content Byt)}}}}

               Es length = "+ Contentbytes.length +" not in [0,125]. ");}
               Gs.dispose ();

                Bufimg.flush ();
                String Savepath = Imagesavepath;
                String visitwebroot = Imagevisitpath;
                Logger.debug ("Savepath:" + Savepath); Logger.debug ("Visitwebroot:" + visitWebroot);
                String osname = System.getproperties (). GetProperty ("Os.name");
                String ContextPath = "/ydmb-external";
                Logger.debug ("Osname:" + osname); if (Osname.startswith ("window") | | osname.startswith ("window")) {Savepath = Pjectpathutil.getabsolute
                    Path ();
                Visitwebroot = ContextPath;
                } logger.debug ("Savepath:" + Savepath);
                String relativepath = "/twocodefile/";
                Savepath = Savepath + relativepath;
                Logger.debug ("Savepath:" + Savepath);
                File File = new file (Savepath);
                if (!file.exists ()) {file.mkdirs ();
                } file.setexecutable (True,false);

                File.setreadable (True,false); String imagetemp = key + ". jpg"; FileName String imagename = relativepath + imagetemp;
Relative folder access name when HTTP access--to access                String ImagePath = Savepath + imagetemp;
                Relative to the server's filename path-to the server used Logger.debug ("imagename:" + imagename);

               Logger.debug ("ImagePath:" + ImagePath);
               Generate a two-dimensional code qrcode picture File Imgfile = new file (ImagePath);
               Imgfile.setexecutable (True,false);

               Imgfile.setreadable (True,false);

               Imageio.write (bufimg, "PNG", imgfile);
               Imgpath = Visitwebroot + imagename;
               Logger.debug ("Imgpath:" + Imgpath);

           Manager.setcacheobject (Two_code_img_key_name + KEY, Imgpath, datatype.string, 3 * 30 * 24 * 60 * 60);
           catch (Exception e) {logger.error ("Generate two-dimensional code picture exception:" + E);
       return imgpath;
 }

}

Pjectpathutil Code:

Package com.leo.common.platform;

Import Java.net.URL;

Import Com.leo.common.platform.config.ConfigResource; /** * Get the project root path * @author Leo * */public class Pjectpathutil {private static ClassLoader ClassLoader = Pjectpathu

    Til.class.getClassLoader ();  public static String Getclasspath () {URL url = classloader.getresource ("/");   WebLogic environment if (url = = null) {URL = Classloader.getresource ("");
    Tomcat Environment} return Url.getpath (); /** * Get Webroot Path/public static string GetAbsolutePath () {String classPath = Getclasspath
        ();
        int index = Classpath.indexof ("/web-inf");
        String path = "";
            if (index = = 1) {//jetty does not have this path index = Classpath.indexof ("/target");
            if (index = = 1) {path = Configresource.getconfig (). GetProperty ("Project.path"); else {path = classpath.substring (0, index) + "/src/main/webapp";
            } else {path = classpath.substring (0, index);
    return path;
    public static void Main (string[] args) {System.out.println (Pjectpathutil.getabsolutepath ());
 }

}

The

Configresource code is as follows:

Package com.leo.common.platform.config;
Import java.util.ArrayList;
Import java.util.List;
Import Java.util.Map;

Import java.util.Properties;

Import Org.apache.log4j.Logger;
Import Com.leo.common.db.DBUtil;

Import Com.leo.common.platform.PlatformSQL; 
 /** * <pre> * Title:ConfigResource.java * Description: Reading public configuration files (config.properties) * Project:leo Project * Copyright:leo.com Copyright (c) 2013 * Company: * </pre> * * @author Leo * @version 2.0 * @date 201

    3-5-2 */public class Configresource {private static Logger log = Logger.getlogger (Configresource.class);

    Private volatile static Properties prop; Private Configresource () {} public static Properties GetConfig () {try {if (prop = null) {synchronized (Configresource.class) {if (prop = null) {Li
st<map<string, object>> list = new arraylist<map<string, object>> ();                        List = Dbutil.gettemplate (). queryForList (Platformsql.all_config);
                        Prop = new Properties ();  For (map<string, object> map:list) {if (Map.get ("key") = = NULL | | map.get ("value") = =
                            NULL) {continue;
                        Prop.put (Map.get ("key"). ToString (), Map.get ("value"). ToString ());
            catch (Exception ex) {log.error (ex);
        Prop = new Properties ();
    return prop;
 }
}
Related Article

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.