Using Java design to generate a two-dimensional code detail tutorial _java

Source: Internet
Author: User
Tags mkdir parent directory

I'll teach you step-by-step. Generate two-dimensional code with Java design

In the era of the Internet of things, two-dimensional code is a very important thing, and now no matter what things must be a two-dimensional code signs, lest outdated, the cops did not use two-dimensional code to identify. Perhaps one day zoning card or hukou will be used to identify the two-dimensional code. Today's whim, see others for their blog added two-dimensional code, I also want to do a test.

Mainly used to achieve two points:

1. Generate a two-dimensional code of any text.

2. Add an image to the middle of a two-dimensional code.

First, the preparatory work.

Prepare the QR two-dimensional Code 3.0 version of the core package and a JPG picture.

Download QR Two-dimensional code packs.

First we have to download the Zxing.jar package, I'm here with the 3.0 version of the core package

Download Address: Now migrated to github:https://github.com/zxing/zxing/wiki/getting-started-developing,

Of course, you can also download jar packs from the Maven warehouse: http://central.maven.org/maven2/com/google/zxing/core/

Second, program design

1, start Eclipse, a new Java project, a good project name (this example named Qrcodesoft). Click Next:

2, Import Zxing.jar package, I am here with the 3.0 version of the core package: Point "add external jar (X) ...".

3, the new two classes, respectively:

Bufferedimageluminancesource.java

Qrcodeutil.java

The key code is: Bufferedimageluminancesource.java and Qrcodeutil.java, where the main method of the test is in Qrcodeutil.java.

Bufferedimageluminancesource.java Program code:

Package Com.yihaomen.barcode;
Import Java.awt.Graphics2D;
Import Java.awt.geom.AffineTransform;

Import Java.awt.image.BufferedImage;

Import Com.google.zxing.LuminanceSource;
	public class Bufferedimageluminancesource extends Luminancesource {private final bufferedimage image;
	private final int left;

	private final int top;
	Public Bufferedimageluminancesource (bufferedimage image) {This (image, 0, 0, image.getwidth (), Image.getheight ());  Public Bufferedimageluminancesource (bufferedimage image, int left, int top, int width, int height) {Super (width,

		height);
		int sourcewidth = Image.getwidth ();
		int sourceheight = Image.getheight (); if (left + width > Sourcewidth | | top + height > sourceheight) {throw new IllegalArgumentException ("Crop R

		Ectangle does not fit within image data. "); for (int y = top; y < top + height; y++) {for (int x = left; x < left + width; + +) {if (Image.getrgb (x, y ) & 0xff000000) = = 0) {IMAGE.SEtrgb (x, y, 0xFFFFFFFF);
		= white}} this.image = new BufferedImage (Sourcewidth, Sourceheight, Bufferedimage.type_byte_gray);
		This.image.getGraphics (). DrawImage (image, 0, 0, NULL);
		This.left = left;
	This.top = top; Public byte[] GetRow (int y, byte[] row {if (Y < 0 | | | y >= getheight ()) {throw new Illegalargumentexcep
		tion ("Requested row is outside the image:" + y);
		int width = getwidth ();
		if (row = = NULL | | Row.length < width) {row = new Byte[width];
		} image.getraster (). getDataElements (left, top + y, width, 1, row);
	return row;
		Public byte[] Getmatrix () {int width = getwidth ();
		int height = getheight ();
		int area = width * height;
		byte[] Matrix = new Byte[area];
		Image.getraster (). getDataElements (left, top, width, height, matrix);
	return matrix;
	public Boolean iscropsupported () {return true; Public Luminancesource crop (int. left, int top, int width, int height) {return new BufFeredimageluminancesource (image, This.left + left, This.top + top, width, height);
	public Boolean isrotatesupported () {return true;
		Public Luminancesource rotatecounterclockwise () {int sourcewidth = Image.getwidth ();
		int sourceheight = Image.getheight ();
		AffineTransform transform = new AffineTransform (0.0, -1.0, 1.0, 0.0, 0.0, sourcewidth);
		BufferedImage rotatedimage = new BufferedImage (Sourceheight, Sourcewidth, Bufferedimage.type_byte_gray);
		Graphics2D g = rotatedimage.creategraphics ();
		G.drawimage (image, transform, null);
		G.dispose ();
		int width = getwidth ();
	Return to New Bufferedimageluminancesource (Rotatedimage, Top, Sourcewidth-(left + width), getheight (), width);
 }
}

Qrcodeutil.java Program code:

Package Com.yihaomen.barcode;
Import Java.awt.BasicStroke;
Import Java.awt.Graphics;
Import Java.awt.Graphics2D;
Import Java.awt.Image;
Import Java.awt.Shape;
Import Java.awt.geom.RoundRectangle2D;
Import Java.awt.image.BufferedImage;
Import Java.io.File;
Import Java.io.OutputStream;
Import java.util.Hashtable;

Import Java.util.Random;

Import Javax.imageio.ImageIO;
Import Com.google.zxing.BarcodeFormat;
Import Com.google.zxing.BinaryBitmap;
Import Com.google.zxing.DecodeHintType;
Import Com.google.zxing.EncodeHintType;
Import Com.google.zxing.MultiFormatReader;
Import Com.google.zxing.MultiFormatWriter;
Import Com.google.zxing.Result;
Import Com.google.zxing.common.BitMatrix;
Import Com.google.zxing.common.HybridBinarizer;

Import Com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
	/** * Two-dimensional Code tool class */public class Qrcodeutil {private static final String CHARSET = "Utf-8";
	private static final String Format_name = "JPG"; Two-dimensional code size private static final int qrcode_size = 300;
	Logo width private static final int width = 60;

	Logo height private static final int height = 60; private static BufferedImage CreateImage (string content, String Imgpath, Boolean needcompress) throws Exception {has
		Htable<encodehinttype, object> hints = new Hashtable<encodehinttype, object> ();
		Hints.put (Encodehinttype.error_correction, ErrorCorrectionLevel.H);
		Hints.put (Encodehinttype.character_set, CHARSET);
		Hints.put (Encodehinttype.margin, 1); 
		Bitmatrix Bitmatrix = new Multiformatwriter (). Encode (content, Barcodeformat.qr_code, qrcode_size, qrcode_size, hints);
		int width = bitmatrix.getwidth ();
		int height = bitmatrix.getheight ();
		BufferedImage image = new BufferedImage (width, height, bufferedimage.type_int_rgb);  for (int x = 0; x < width, x + +) {for (int y = 0; y < height; y++) {Image.setrgb (x, Y, Bitmatrix.get (x, y)?
			0XFF000000:0XFFFFFFFF); } if (Imgpath = null | |
		"". Equals (Imgpath)) {return image;}//Insert Picture qrcodeutil.insertimage (image, Imgpath, needcompress);
	return image; 
	 /** * Insert Logo * * @param source * Two-dimensional code picture * @param Imgpath * Logo image Address * @param needcompress * Whether compression * @throws Exception */private static void Insertimage (BufferedImage source, String Imgpath, Boolean needcompress
		) throws Exception {File File = new file (Imgpath); if (!file.exists ()) {System.err.println ("+imgpath+") the file does not exist!
			");
		Return
		Image src = imageio.read (new File (Imgpath));
		int width = src.getwidth (null);
		int height = src.getheight (null);
			if (needcompress) {//Compress logo if (width > width) {width = width;
			} if (height > height) {height = height;
			Image image = Src.getscaledinstance (width, height, image.scale_smooth);
			BufferedImage tag = new BufferedImage (width, height, bufferedimage.type_int_rgb);
			Graphics g = tag.getgraphics (); G.drawimage (image, 0, 0, NULL);
			Draw the reduced figure g.dispose (); src = iMage
		}//Insert logo graphics2d graph = source.creategraphics ();
		int x = (qrcode_size-width)/2;
		int y = (qrcode_size-height)/2;
		Graph.drawimage (src, x, y, width, height, null);
		Shape shape = new Roundrectangle2d.float (x, y, Width, width, 6, 6);
		Graph.setstroke (New Basicstroke (3f));
		Graph.draw (Shape);
	Graph.dispose ();
	 /** * Generate two-dimensional code (embedded logo) * * @param content * Contents * @param imgpath * Logo address * @param destpath * Storage Directory * @param needcompress * Compressed logo * @throws Exception/public static void encode (string content, String Imgpat H, String destpath, Boolean needcompress) throws Exception {bufferedimage image = qrcodeutil.createimage (content, IM
		Gpath, needcompress);
		Mkdirs (DestPath);
		String file = new Random (). Nextint (99999999) + ". jpg";
	Imageio.write (image, Format_name, new File (destpath+ "/" +file)); /** * When a folder does not exist, Mkdirs automatically creates a multi-tiered directory, distinguished from mkdir.
	(MkDir throws an exception if the parent directory does not exist) * @author Lanyuan * email:mmm333zzz520@163.com * @date 2013-12-11 Morning 10:16:36 * @param destpath Storage Directory * * public static void Mkdirs (String destpath) {File file =ne 
		W File (DestPath); When a folder does not exist, Mkdirs automatically creates a multi-tiered directory, distinguished from mkdir.
		(MkDir throws an exception if the parent directory does not exist) if (!file.exists () &&!file.isdirectory ()) {file.mkdirs (); /** * Generate two-dimensional code (embedded logo) * * @param content * Contents * @param imgpath * Logo address * @param destpath * Store Address * @throws Exception */public static void encode (string content, String Imgpath, String destpath) throws Except
	Ion {Qrcodeutil.encode (content, Imgpath, DestPath, false);
	 /** * Generate a two-dimensional code * * @param content * @param destpath * Storage Address * @param needcompress * Whether compression logo * @throws Exception */public static void encode (string content, String DestPath, Boolean needcompress) throws Exce
	ption {qrcodeutil.encode (content, NULL, destpath, needcompress);
/** * Generate a two-dimensional code * * @param content * @param destpath * Storage address * @throws Exception	 */public static void encode (string content, String destpath) throws Exception {qrcodeutil.encode (content, null, des
	Tpath, false);  /** * Generate two-dimensional code (embedded logo) * * @param content * Contents * @param imgpath * Logo address * @param output stream *
			@param needcompress * is compressed logo * @throws Exception/public static void encode (string content, String Imgpath, OutputStream output, Boolean needcompress) throws Exception {bufferedimage image = Qrcodeutil.createimage (content, I
		Mgpath, needcompress);
	Imageio.write (image, format_name, output); /** * Generates a two-dimensional code * * @param content * @param output * @throws Exception/public static V
	OID encode (String content, OutputStream output) throws Exception {qrcodeutil.encode (content, NULL, output, false); /** * Parse Two-dimensional code * * @param file * Two-dimensional code picture * @return * @throws Exception/public static String decode (Fil
		E file) throws Exception {bufferedimage image; Image = Imageio.read (file);
		if (image = = null) {return null;
		} bufferedimageluminancesource Source = new Bufferedimageluminancesource (image);
		Binarybitmap bitmap = new Binarybitmap (new Hybridbinarizer (source));
		result result;
		Hashtable<decodehinttype, object> hints = new Hashtable<decodehinttype, object> ();
		Hints.put (Decodehinttype.character_set, CHARSET);
		result = new Multiformatreader (). Decode (bitmap, hints);
		String resultstr = Result.gettext ();
	return resultstr; /** * Parse the two-dimensional code * * @param path * Two-dimensional code picture address * @return * @throws Exception/public static String decode (S
	Tring path) throws Exception {return Qrcodeutil.decode (new File (path));
		public static void Main (string[] args) throws Exception {String text = "http://www.yihaomen.com";
	Qrcodeutil.encode (text, "C:/me.jpg", "C:/barcode", true);
 }
}

Generate a two-dimensional code with no logo

The program code is as follows:

public static void Main (string[] args) throws Exception {
  String text = "http://www.dans88.com.cn";
  Qrcodeutil.encode (Text, "", "D:/myworkdoc", True);
}

Run this test method, the generated two-dimensional code without logo, the style is as follows:

I'd be interested in a cellphone scan.

Generate a two-dimensional code with logo

Logo can use their own avatar, or a picture of their favorite can be, using the following code, the program code is as follows:

public static void Main (string[] args) throws Exception {
  String text = "http://www.dans88.com.cn";
  Qrcodeutil.encode (text, "D:/myworkdoc/my180.jpg", "D:/myworkdoc", true);
 

The only difference is that, on the basis of the previous designation of the address of the logo, where the test using the C-disk picture file

Use the mobile phone scan, can appear to appear text, click on to enter their own website.

The above is to use Java design to generate two-dimensional code, interested friends can refer to, thank you all for the support of this site!

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.