Java zxing generation of two-dimensional code learning __java

Source: Internet
Author: User

Java zxing generation of two-dimensional code learning


1. Generate two-dimensional code without logo

Import Java.awt.image.BufferedImage;
Import Java.io.File;

Import java.io.IOException;

Import Javax.imageio.ImageIO;
Import Com.google.zxing.BarcodeFormat;
Import Com.google.zxing.Binarizer;
Import Com.google.zxing.BinaryBitmap;
Import com.google.zxing.ChecksumException;
Import com.google.zxing.FormatException;
Import Com.google.zxing.LuminanceSource;
Import com.google.zxing.NotFoundException;
Import Com.google.zxing.Result;
Import com.google.zxing.WriterException;
Import Com.google.zxing.client.j2se.BufferedImageLuminanceSource;
Import Com.google.zxing.client.j2se.MatrixToImageWriter;
Import Com.google.zxing.common.BitMatrix;
Import Com.google.zxing.common.HybridBinarizer;
Import Com.google.zxing.qrcode.QRCodeReader;



Import Com.google.zxing.qrcode.QRCodeWriter;
		public class Qrcodewithoutlogo {public static void main (string[] args) {String content = "content";
			try {content = new String (content.getbytes ("UTF-8")); String ImagePath = "c:\\users\\administrator\\desktop\\Ssx.png ";
			File File = new file (ImagePath);
			Qrcodewriter writer = new Qrcodewriter ();
			Generate two-dimensional code ↓bitmatrix matrix = Writer.encode (content,barcodeformat.qr_code,400,400);
			Matrixtoimagewriter.writetofile (Matrix, "PNG", file);
			Generate two-dimensional code ↑//read two-dimensional code ↓qrcodereader reader = new Qrcodereader ();
			BufferedImage image = Imageio.read (file);
			Luminancesource Source = new Bufferedimageluminancesource (image);
			Binarizer Binarizer = new Hybridbinarizer (source);
			Binarybitmap Imagebinarybitmap = new Binarybitmap (Binarizer);
			Result result = Reader.decode (IMAGEBINARYBITMAP);
			System.out.println (Result.tostring ());
			System.out.println (Result.getbarcodeformat ());
			System.out.println (Result.gettext ()); Read two-dimensional code ↑ catch (writerexception| IOException | notfoundexception | checksumexception |
		FormatException e) {e.printstacktrace (); }
	}
}


2. Generate a two-dimensional code with logo

Reference: http://blog.csdn.net/lcx46/article/details/13626841

Import Java.awt.Color;
Import Java.awt.Graphics2D;
Import Java.awt.Image;
Import Java.awt.geom.AffineTransform;
Import java.awt.image.AffineTransformOp;
Import Java.awt.image.BufferedImage;
Import Java.io.File;
Import java.io.IOException;
Import Java.util.HashMap;

Import Java.util.Map;

Import Javax.imageio.ImageIO;
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;
	public class Qrcodewithlogo {//logo picture width private static final int image_width = 80;
	
	private static final int image_height = 80;
	
	private static final int image_half_width = IMAGE_WIDTH/2;

	Padding width private static final int frame_width = 2;

	Two-dimensional code writer private static Multiformatwriter mutiwriter = new Multiformatwriter (); public static void Encode (string content, int width, int height, string srciMagepath, String Destimagepath) {try {imageio.write (content, width, height, srcimagepath), "PNG", n
		EW File (Destimagepath));
		catch (IOException e) {e.printstacktrace ();
		catch (Writerexception e) {e.printstacktrace (); } private static BufferedImage Genbarcode (string content, int width, int height, String srcimagepath) throws Write Rexception, IOException {//Read source image BufferedImage Scaleimage = scale (Srcimagepath, Image_width, Image_height, tr
		UE);
		int[][] Srcpixels = new Int[image_width][image_height]; for (int i = 0; i < scaleimage.getwidth (); i++) {for (int j = 0; J < Scaleimage.getheight (); j + +) {Srcpixel
			S[I][J] = Scaleimage.getrgb (i, j);
		} map<encodehinttype, object> hint = new Hashmap<encodehinttype, object> ();
		Hint.put (Encodehinttype.character_set, "utf-8");
		Hint.put (Encodehinttype.error_correction, ErrorCorrectionLevel.H); Generate a two-dimensional code Bitmatrix matrix = mutiwriter.encode (content,Barcodeformat.qr_code, width, height, hint);
		The two-dimensional matrix is converted into one dimensional pixel Group int halfw = Matrix.getwidth ()/2;
		int halfh = Matrix.getheight ()/2;

		int[] pixels = new int[width * height]; for (int y = 0; y < matrix.getheight (); y++) {for (int x = 0; x < Matrix.getwidth (), + + +) {//) read picture if ( X > Halfw-image_half_width && x < HALFW + image_half_width && y > Halfh-image_hal F_width && y < HALFH + image_half_width) {Pixels[y * WIDTH + x] = SRCPIXELS[X-HALFW + imag
				E_HALF_WIDTH][Y-HALFH + image_half_width]; ///In picture four weeks to form a border else if (x > Halfw-image_half_width-frame_width && x < halfw-image_half_ WIDTH + frame_width && y > Halfh-image_half_width-frame_width && y < HALFH + Image_h Alf_width + frame_width) | |
							(x > HALFW + image_half_width-frame_width && x < HALFW + Image_half_width + frame_width	&& y > Halfh-image_half_width-frame_width && y < HALFH + image_half_width + frame_width )
						|| (x > Halfw-image_half_width-frame_width && x < HALFW + image_half_width + frame_width &A
						mp;& y > Halfh-image_half_width-frame_width && y < halfh-image_half_width + frame_width) || (x > Halfw-image_half_width-frame_width && x < HALFW + image_half_width + frame_width &A mp;& y > halfh + image_half_width-frame_width && y < HALFH + image_half_width + frame_width)
				{Pixels[y * width + x] = 0XFFFFFFF; else {//Here you can modify the color of the two-dimensional code, you can set the color of two-dimensional code and background respectively; Pixels[y * width + x] = Matrix.get (x, y)? 0xff000000:0xfffff
				ff
		}} bufferedimage image = New BufferedImage (width, height, bufferedimage.type_int_rgb);

		Image.getraster (). setDataElements (0, 0, width, height, pixels);
	return image;
	}

	/** * To scale the incoming original image by height and width, generate the icon that meets the requirement * * @param srcimagefile * source file Address * @param height * Target height * @param width * @param hasfiller * If the ratio is incorrect if filler is required: true for filler;
	 False is not filler; * @throws IOException */private static BufferedImage scale (String srcimagefile, int height, int width, Boolean hasf
		Iller) throws IOException {double ratio = 0.0;//Scaling File = new file (srcimagefile);
		BufferedImage srcimage = imageio.read (file);
		Image destimage = srcimage.getscaledinstance (width, height, bufferedimage.scale_smooth); Calculate scale if (srcimage.getheight () > height) | | (Srcimage.getwidth () > width)) {if (Srcimage.getheight () > Srcimage.getwidth ()) {ratio = (new Integer (height)). Doublevalue ()/Srcimage
			. GetHeight ();
			else {ratio = (new Integer (width)). Doublevalue ()/srcimage.getwidth (); } affinetransformop op = new Affinetransformop (affinetransform.getscaleinstance (ratio, RATIO), NULL);
		Destimage = Op.filter (srcimage, NULL);
			} if (Hasfiller) {//filler bufferedimage image = new BufferedImage (width, height, bufferedimage.type_int_rgb);
			Graphics2D graphic = Image.creategraphics ();
			Graphic.setcolor (Color.White);
			Graphic.fillrect (0, 0, width, height); 
						if (width = = destimage.getwidth (null)) Graphic.drawimage (destimage, 0, (Height-destimage.getheight (NULL))/2,
			Destimage.getwidth (NULL), destimage.getheight (null), color.white, NULL); else Graphic.drawimage (Destimage, (Width-destimage.getwidth (NULL))/2, 0, destimage.getwidth (null), des
			Timage.getheight (null), color.white, NULL);
			Graphic.dispose ();
		Destimage = image;
	Return (bufferedimage) destimage; public static void Main (string[] args) {Qrcodewithlogo.encode ("http://www.baidu.com", +, "c:/users/admin")
	Istrator/desktop/src.png "," c:/users/administrator/desktop/des.png ");
 }
}

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.