The function and features of QR code and the use of Java to generate a QR code with logo

Source: Internet
Author: User
Tags string format

The two-dimensional barcode/two-D code (2-dimensional bar code) is a black-and- white graphic that distributes the data symbol information in a plane (two-dimensional direction) with a particular geometry , and skillfully utilizes the "0" that constitutes the internal logical basis of the computer. "," 1 "bitstream concept, using a number of geometric shapes corresponding to the binary to represent the text value information, through the image input device or photoelectric scanning equipment automatically read to realize automatic Processing: It has some common features of bar code technology: Each code system has its own specific character set; Each character occupies a certain width , with a certain calibration function. At the same time, it also has the function of information automatic recognition for different lines and the change point of processing graphics rotation.

1. Two-dimensional code key features

Two-dimensional bar code is a high-density, highly informative portable data file, is the realization of documents and cards, such as large-capacity, high-reliability information automatically stored, carried and can be used to automatically read the ideal means of machine. The two-dimensional barcode has the following characteristics:

1, the information capacity is large according to the different bar-space ratio can accommodate 250 to 1100 characters per square inch. In the International standard card effective area (equivalent to 2/3 of the credit card area, about 500 Chinese characters information. This two-dimensional barcode information capacity is dozens of times times higher than ordinary barcode, also higher than magnetic card.

2, coding range of the two-dimensional barcode can be photographs, fingerprints, palm prints, signatures, sounds, text, etc. can be digitized information encoded.

3, confidentiality, security performance good two-dimensional barcode with information can not be rewritten, such as multiple security features, it may use password anti-counterfeiting, software encryption and the use of information such as fingerprints, photos and other anti-counterfeiting, so with strong security security performance.

4. The decoding error rate of high decoding reliability is about 2%, while the ber of two-dimensional bar code is not more than one out of 10,000, and the decoding reliability is very high.

5, correction error ability strong two-dimensional barcode using the world's most advanced digital error correction theory, if the damage area of not more than 50%, bar code due to contamination, damage and other lost information, can be deciphered as usual.

6, easy to make and low cost using the existing lattice, laser, inkjet, thermal/thermal transfer, business card printing technology, you can print on paper, cards, PVC, and even metal surface of the two-dimensional barcode. The increase in costs is only the cost of ink.

7, the shape of the barcode symbol variable the same amount of information, two-dimensional barcode shape can be based on the size of the vector and art design and other self-adjustment.

2. QRCode

QR (quick-response) code is widely used in a two-dimensional code, decoding speed fast. It can store multi-use types. such as when a qrcode the basic structure, wherein:

I. Surveying graphics, position detection graphics separators, positioning graphics: for the two-dimensional code positioning, for each QR code, the location is fixed existence, but the size of the specifications will be different;

II. Correction Graphics: The specification is determined, the number and position of the corrected graph are determined;

Iii. format information: The error correction level of the modified QR code is divided into L, M, Q, H;

Iv. version information: That is, two-dimensional code specifications, QR code symbols have a total of 40 specifications of the matrix (generally black and white), from 21x21 (version 1), to 177x177 (version 40), each version of the symbol than the previous version of each side of the addition of 4 modules.

V. Data and Error Correction code word: The actual saved QR code information, and error correction code word (used to correct the damage caused by the two-dimensional code).

More QR code generation details can be stamped here


3. Two-dimensional code generation with center logo image

Use a jar package that first imports Google Open source zxing and J2SE

(1) data model of two-dimensional code

Package com.    Lin;public class QRCode {private String content;   Two-dimensional code content private String FilePath;   File storage path private String fileName;         File name private int width;     Image width private int height;     Image height private String format;  Image type, eg:pngprivate int onColor = 0xff000000; The default is black private int offcolor = 0xFFFFFFFF; Background color, default white//parameterless constructor public QRCode () {}public String getcontent () {return content;} public void SetContent (String content) {this.content = content;} Public String GetFilePath () {return filePath;} public void SetFilePath (String filePath) {this.filepath = FilePath;} Public String GetFileName () {return fileName;} public void Setfilename (String fileName) {this.filename = FileName;} public int getwidth () {return width;} public void setwidth (int width) {this.width = width;} public int getheight () {return height;} public void setheight (int height) {this.height = height;} Public String GetFormat () {return format;} public void SetFormat (String format) {this.format = format;} public int GEToncolor () {return onColor;} public void Setoncolor (int onColor) {this.oncolor = OnColor;} public int Getoffcolor () {return offcolor;} public void Setoffcolor (int offcolor) {this.offcolor = Offcolor;}}


(2) generate two-dimensional code image

/** * Generate two-dimensional code image * @param q QR code model * @param the storage path of Logopath Center logo, NULL when no center logo * @throws writerexception * @throws IOException */public void encode (QRCode Q, String Logopath) throws Writerexception, IOException {Bitmatrix Bitmatr            ix          Hashtable<encodehinttype, integer> hints = new hashtable<> (); Hints.put (Encodehinttype.margin, 1); Set the size of the blank border of the QR code 1-4,1 is the minimum 4 is the default GB//build Matrix Bitmatrix = new Multiformatwriter (). Encode (New String (Q.getcontent ().          GetBytes ("UTF-8"), "iso-8859-1"), Barcodeformat.qr_code, Q.getwidth (), Q.getheight (), hints);                 Storage paths Path Path = Filesystems.getdefault (). GetPath (Q.getfilepath (), Q.getfilename ());                Matrix color settings Matrixtoimageconfig config = new Matrixtoimageconfig (Q.getoncolor (), Q.getoffcolor ());                BufferedImage image = Matrixtoimagewriter.tobufferedimage (Bitmatrix, config); if (null = = Logopath) {//Do not need Center logo imageio.write (Image, Q.getformat (), New File (Path.tostring ()));        }else{this.overlapimage (image, Path.tostring (), Logopath, Q.getformat ());       } System.out.println ("Success"); }

(3) Add logo in QR Code center

/** * Add center graphics to generated QR code * @param image * @param imgsavepath * @param logopath * @param format */public void Overlapimage (Buffe Redimage image, String Imgsavepath, String Logopath, string format) {try {BufferedImage logo = scale (Logopath, IMAGE.GETWI DTH ()/5,image.getheight ()/5, true); Graphics2D g = image.creategraphics ()//logo width int width = image.getwidth ()/5;int height = image.getheight ()/5;//logo start Position, this is to center the logo int x = (Image.getwidth ()-width)/2;int y = (image.getheight ()-height)/2;g.drawimage (logo, x, y, WI DTH, height, null); G.dispose (); Imageio.write (image, format, new File (Imgsavepath));} catch (Exception e) {e.printstacktrace ();}}

(4) zoom the original image to the appropriate size
/** * Scales the incoming original image by height and width, generates an icon that meets the requirements * @param srcimagefile source file address * @param height target height * @param width target width * @param if the hasfiller ratio is not correct, the filler is required: true for filler; False for non-filler; * @throws ioexception */private static bufferedimage scale (String srcimagefile, int height,int width, boolean hasfiller) t Hrows IOException {Double ratio = 0.0;//scale file = new file (srcimagefile); BufferedImage srcimage = imageio.read (file), Image destimage = srcimage.getscaledinstance (width, height, Bufferedimage.scale_smooth);//Calculate proportional 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);d Estimage = 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), Elsegraphic.drawimage (Destimage, (Width- Destimage.getwidth (NULL))/2, 0,destimage.getwidth (null), destimage.getheight (null), color.white, NULL); Graphic.dispose ();d estimage = image;} Return (BufferedImage) destimage;}


4. Decoding of two-D codes

/**  * Parse image * @param  filePath qr  code storage Path * @throws ioexception  * @throws notfoundexception   * * public void decode (String filePath) throws IOException, notfoundexception {     bufferedimage image;          Image = Imageio.read (new File (FilePath));           Luminancesource Source = new Bufferedimageluminancesource (image);           Binarizer Binarizer = new Hybridbinarizer (source);           Binarybitmap Binarybitmap = new Binarybitmap (binarizer);           Map<decodehinttype, object> hints = new Hashmap<decodehinttype, object> ();           Hints.put (Decodehinttype.character_set, "UTF-8");           Result result = new Multiformatreader (). Decode (Binarybitmap, hints);//decode the image           System.out.println ("Picture content:  ");           System.out.println (Result.gettext ());      }

5. Example of generating a QR code

Package com. Lin;import Java.io.ioexception;import Com.google.zxing.notfoundexception;import com.google.zxing.WriterException; public class Test {public static void main (string[] args) throws Writerexception, IOException, notfoundexception {Testqrco De t = new testqrcode ();//The encapsulation of the QR code data facilitates the separation of the data from the business logic qrcode q = new QRCode (); Q.setcontent ("How I want to see You"); Q.setfilepath ("d:// "); Q.setfilename (" 1.png "); Q.setheight ($); Q.setwidth (+); Q.setformat (" png "); Q.setoncolor (0xff4169e1)   ; Royal bluestring Logopath = "D://1.jpg"; T.encode (q, Logopath);//t.decode ("D://1.png");}}

jar packages for zxing and J2SE, Project code and application examples on GitHub

Generated QR code effect:




The function and features of QR code and the use of Java to generate a QR code with logo

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.