Using zxing to generate two-dimensional code in batches

Source: Internet
Author: User

Use zxing batch in a well-done position on the background map, the specified text content (link address, text, etc.) generated two-dimensional code and placed in the position,

Finally, add the card number.

Steps:

1). Make a good background map, such as:


2). Generate two-dimensional code bufferedimage objects. The code is as follows:

/** *  * @Title: Tobufferedimage * @Description: Convert text into QR code picture Object * @param text * QR            code content * @param width * qr            code Height * @ Param Height *            two-bit width * @param * @param Exception *            settings file * @return bufferedimage return type * @throws */public static Buff Eredimage tobufferedimage (String text, int width,int height) throws Exception {int BLACK = 0xff000000;int White = 0xFFFFFF FF; Hashtable<encodehinttype, object> hints = new Hashtable<encodehinttype, object> (); Hints.put ( Encodehinttype.character_set, "Utf-8"); The content uses the character set encoding Hints.put (Encodehinttype.margin, 1); Bitmatrix matrix = new Multiformatwriter (). Encode (Text,barcodeformat.qr_code, width, height, hints); BufferedImage image = new BufferedImage (width, height,bufferedimage.type_int_rgb); for (INT x = 0; x < width; + +) {for (int y = 0; y < height; y++) {Image.setrgb (x, Y, Matrix.get (x, y)? black:white);}} return image;


3). Create a QR code at the specified position on the background map, as follows:

/** * * @Title: Markimagebycode * @Description: Add two-D code to the position assigned to the picture * @param img * QR Code Image Object * @param srcimgpath *            Background map * @param targerpath * Target map * @param positionwidth * Position Horizontal axis * @param positionheight * Position ordinate * @return void return type * @throws */public static void Markimagebycode (Image img, String srcimgpath,string targe RPath, int positionwidth, int positionheight) {OutputStream os = null;try {Image srcimg = imageio.read (New File (Srcimgpath )); BufferedImage buffimg = new BufferedImage (Srcimg.getwidth (null), srcimg.getheight (null), BUFFEREDIMAGE.TYPE_INT_RGB) ;//1, get the Brush object graphics2d g = Buffimg.creategraphics ();//2, set the jagged edge of the segment G.setrenderinghint (Renderinghints.key_ Interpolation,renderinghints.value_interpolation_bilinear); G.drawimage (Srcimg.getscaledinstance ( Srcimg.getwidth (NULL), srcimg.getheight (null), Image.scale_smooth), 0, 0,null); G.setcomposite ( Alphacomposite.getinstance (Alphacomposite.src_atop,alpha));//3, QR code position g.drawimage (IMG, Positionwidth, positionheight, null); G.setcomposite (Alphacomposite.getinstance (Alphacomposite.src_over));//4, releasing Resources g.dispose ( );//5, Generate images (PNG is recommended, JPG will be distorted) OS = new FileOutputStream (Targerpath); Imageio.write (buffimg, "PNG", OS); System.out.println ("QR Code image Generation Success");} catch (Exception e) {e.printstacktrace ();} finally {try {if (null! = OS) os.close ()} catch (Exception e) {E.printstacktrac E ();}}}


4). Add the Standing card number to the card

/** * * @Title: Presstext * @Description: Add text to a picture @param presstext * Text content * @param srcimagefile *            Original picture * @param destimagefile * Target picture * @param x * Horizontal Axis * @param y * ordinate * @param alpha * Transparency * @return void return type * @throws */public final static void Presstext (String presstext, String srcimagefile,st Ring destimagefile, int x, int y, float Alpha) {try {file img = new File (srcimagefile); Image src = Imageio.read (img); int W Idth = Src.getwidth (null); int height = src.getheight (null); BufferedImage image = new BufferedImage (width, height,bufferedimage.type_int_rgb); Graphics2D g = image.creategraphics ();//Open Text anti-aliasing to text Burr G.setrenderinghint (renderinghints.key_text_antialiasing, RENDERINGHINTS.VALUE_TEXT_ANTIALIAS_ON); g.drawimage (src, 0, 0, width, height, null);//Set color G.setcolor (new color (89, 87 , 87));//Set Fontg.setfont (New Font ("_GBK", Font.Bold)); G.setcomposite (Alphacomposite.getinstance ( Alphacomposite.src_atop,alpha));//FirstThe contents of one parameter, and the coordinate position (x, y) of the text on the picture, followed by two parameters. g.DrawString (Presstext, x, y); G.dispose (); Imageio.write (bufferedimage Image, "PNG", new File (Destimagefile));//output to file stream} catch (Exception e) {e.printstacktrace ()}}

Example:

Code:

Test code

public class Codetest {public static void main (string[] args) throws Exception {String text = "http://www.xxx.com/";//Two D Code content//Generate two-dimensional code//generate picture two-dimensional code storage directory String TargetPath = "f:/qrcode/targetimg/" + utils.tostr ();//Create Directory Utils.makedirs (TargetPath); int begin = 100;//code start digit int end = 101;//code end number for (int i = begin; I <= end; i++) {//Generate 16 digits with date such as 20161214000001Stri ng code = UTILS.TOSTR () + utils.formatenumber (i);//Get QR code object BufferedImage image = Utils.tobufferedimage (text+ "? paycode=" + code,240,240);//Generate a Utils.markimagebycode (image, "F:/qrcode/srcimg/src.png", TargetPath + "/" + code + ") with a background image and a two-dimensional code. PNG ", 340, 160);//The chart of the card plus the code number utils.presstext (code, TargetPath +"/"+ code +". png ", targetpath+"/"+ code +". png ", 390 , 417, 0.5f);} Generate two-dimensional code}}

Effect:

The batch-generated images are as follows

Batch chart:

Utils Code:

Package Cn.utils.code;import Java.awt.alphacomposite;import Java.awt.color;import java.awt.font;import Java.awt.graphics2d;import Java.awt.image;import Java.awt.renderinghints;import java.awt.image.BufferedImage; Import Java.io.file;import java.io.fileoutputstream;import java.io.outputstream;import Java.text.DecimalFormat; Import Java.text.simpledateformat;import java.util.date;import java.util.hashtable;import Javax.imageio.ImageIO; Import Com.google.zxing.barcodeformat;import Com.google.zxing.encodehinttype;import Com.google.zxing.multiformatwriter;import com.google.zxing.common.bitmatrix;/** Tool class.  */public abstract class Utils {/** date format: yyyy-mm-dd HH:mm:ss */public static String df_datetime = "YyyyMMdd";p rivate static  float Alpha = 1f;/** * * @Title: Tobufferedimage * @Description: Convert text to QR code picture Object * @param text * QR Code content * @param Width * Two-dimensional code height * @param Height * Two-bit width * @param * @param Exception * settings file * @return Buffer Edimage return type * @throws */publiC Static BufferedImage tobufferedimage (String text, int width,int height) throws Exception {int BLACK = 0xff000000;int WHI TE = 0xFFFFFFFF; Hashtable<encodehinttype, object> hints = new Hashtable<encodehinttype, object> (); Hints.put ( Encodehinttype.character_set, "Utf-8"); The content uses the character set encoding Hints.put (Encodehinttype.margin, 1); Bitmatrix matrix = new Multiformatwriter (). Encode (Text,barcodeformat.qr_code, width, height, hints); BufferedImage image = new BufferedImage (width, height,bufferedimage.type_int_rgb); for (INT x = 0; x < width; + +) {for (int y = 0; y < height; y++) {Image.setrgb (x, Y, Matrix.get (x, y)? black:white);}} return image;            /** * * @Title: Markimagebycode * @Description: Add two-D code to the position assigned to the picture * @param img * QR Code Image Object * @param srcimgpath *            Background map * @param targerpath * Target map * @param positionwidth * Position Horizontal axis * @param positionheight * Position ordinate * @return void return type * @throws */public static void Markimagebycode (Image img, String SRcimgpath,string targerpath, int positionwidth, int positionheight) {OutputStream os = null;try {Image srcimg = ImageIO.rea D (New File (Srcimgpath)); BufferedImage buffimg = new BufferedImage (Srcimg.getwidth (null), srcimg.getheight (null), BUFFEREDIMAGE.TYPE_INT_RGB) ;//1, get the Brush object graphics2d g = Buffimg.creategraphics ();//2, set the jagged edge of the segment G.setrenderinghint (Renderinghints.key_ Interpolation,renderinghints.value_interpolation_bilinear); G.drawimage (Srcimg.getscaledinstance ( Srcimg.getwidth (NULL), srcimg.getheight (null), Image.scale_smooth), 0, 0,null); G.setcomposite ( Alphacomposite.getinstance (Alphacomposite.src_atop,alpha));//3, QR code position g.drawimage (IMG, Positionwidth, Positionheight, NULL); G.setcomposite (Alphacomposite.getinstance (Alphacomposite.src_over));//4, releasing Resources g.dispose (); /5, Generate picture (proposed PNG, JPG will be distorted) OS = new FileOutputStream (Targerpath); Imageio.write (buffimg, "PNG", OS); System.out.println ("QR Code image Generation Success");} catch (Exception e) {e.printstacktrace ();} finally {try {if (null! = OS) os.close ();} catch (ExceptIon e) {e.printstacktrace ();}}}            /** * * @Title: Presstext * @Description: Add text to a picture @param presstext * Text content * @param srcimagefile *            Original picture * @param destimagefile * Target picture * @param x * Horizontal Axis * @param y * ordinate * @param alpha * Transparency * @return void return type * @throws */public final static void Presstext (String presstext, String srcimagefile,st Ring destimagefile, int x, int y, float Alpha) {try {file img = new File (srcimagefile); Image src = Imageio.read (img); int W Idth = Src.getwidth (null); int height = src.getheight (null); BufferedImage image = new BufferedImage (width, height,bufferedimage.type_int_rgb); Graphics2D g = image.creategraphics ();//Open Text anti-aliasing to text Burr G.setrenderinghint (renderinghints.key_text_antialiasing, RENDERINGHINTS.VALUE_TEXT_ANTIALIAS_ON); g.drawimage (src, 0, 0, width, height, null);//Set color G.setcolor (new color (89, 87 , 87));//Set Fontg.setfont (New Font ("_GBK", Font.Bold)); G.setcomposite (Alphacomposite.getinstance (AlphaComposite.src_atop,alpha));//The contents of the setting, the first parameter, and the coordinate position (x, y) of the text on the picture, followed by two parameters. g.DrawString (Presstext, x, y); G.dispose ( ); Imageio.write ((bufferedimage) image, "PNG", new File (Destimagefile));//output to file stream} catch (Exception e) { E.printstacktrace ();}} Date-to-string/** formats the date as a string, the default format is Yyyy-mm-dd HH:mm:ss, and the default date is the current date. */public static String Tostr () {return tostr (df_datetime);} /** formats the date as a string, the format is specified by the parameter format, the default date is the current date, and the format value can use this class of constants or customizations. */public static string Tostr (string format) {return TOSTR (format, New Date ());} /** formats the date as a string, the default format is Yyyy-mm-dd HH:mm:ss, and the date is specified by the parameter date. */public static String tostr (date date) {return tostr (df_datetime, date);} /** formats the date as a string, the format is specified by the parameter format, the date is specified by the parameter date, and the format value can use this class of constants or customizations. */public static string Tostr (string format, date date) {return new SimpleDateFormat (format). format (date); public static String formatenumber (int num) {DecimalFormat df = new DecimalFormat ("000000"); String str2 = Df.format (num); return str2;} public static Boolean makedirs (String filePath) {File folder = NEW File (FilePath); return (Folder.exists () && folder.isdirectory ())? True:folder.mkdirs ();}}

the technology used:

1. Use the zxing to generate the QR Code tool.

1):

http://repo1.maven.org/maven2/com/google/zxing/javase/3.1.0/

2). MAVEN Configuration

<dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId>< Version>2.2</version></dependency>


---------------------------------------------------------------------------Copyright Notice------------------------------------------ ------------------------------------------------


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced. Blog Address: http://blog.csdn.net/mr_smile2014




Using zxing to generate two-dimensional code in batches

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.