Java QR code, java

Source: Internet
Author: User

Java QR code, java

Recently, I suddenly wanted to write some blogs, so I wrote some technical code that I felt useful and you may also use. It facilitates mutual learning and communication.

Today's blog mainly uses Java to implement the QR code:

Before writing code, let's talk about the overall idea to implement functions more conveniently and quickly.

(1) first of all to achieve the QR code function needs to import com. google. zxing core jar package, I import here is the core-3.2.1.jar;

(2) The so-called QR code is to put the required content into an image, so here we first create an image with the parameter content, the method is as follows:

Private static BufferedImage createImage (String content, String imgPath, boolean needCompress) throws Exception {
Hashtable <EncodeHintType, Object> hints = new Hashtable <EncodeHintType, Object> ();
Hints. put (EncodeHintType. ERROR_CORRECTION, ErrorCorrectionLevel. H); // response rate: the higher the response rate, the more valid pixels the QR code has.
Hints. put (EncodeHintType. CHARACTER_SET, CHARSET); // use lower-case encoding. content starting with] Q2 \ 000026 will appear in upper case.
Hints. put (EncodeHintType. MARGIN, 1); // set the margin border
BitMatrix bitMatrix = new MultiFormatWriter (). encode (content, BarcodeFormat. QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
Hints); // QR code matrix
Int width = bitMatrix. getWidth ();
Int height = bitMatrix. getHeight ();
BufferedImage image = new BufferedImage (width, height, BufferedImage. TYPE_INT_RGB); // put the QR code matrix into the image stream to generate an image
For (int x = 0; x <width; x ++ ){
For (int y = 0; y Image. setRGB (x, y, bitMatrix. get (x, y )? 0xFF000000: 0 xFFFFFFFF); // fill, you can set the color value to the last 6 digits
}
}
If (imgPath = null | "". equals (imgPath )){
Return image;
}
// Insert an image
QRCodeUtil. insertImage (image, imgPath, needCompress );
Return image;
}

// Insert a logo. If you do not need a logo, do not execute this method.

Private static void insertImage (BufferedImage source, String imgPath, boolean needCompress) throws Exception {
File file = new File (imgPath );
If (! File. exists ()){
System. err. println ("" + imgPath + "this 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 graph.
G. dispose ();
Src = image;
}
// Insert the 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); // The following two parameters are used to set the peripheral rounded corner. The larger the value, the larger the rounded corner.
Graph. setStroke (new BasicStroke (3f ));
Graph. draw (shape );
Graph. dispose ();
}

(3) At this point, the method for generating a QR code image is finished. Is it very simple? Next, call this method.

/**
* Generate a QR code (embedded LOGO)
*
* @ Param content
* Content
* @ Param imgPath
* LOGO address
* @ Param destPath
* Storage directory
* @ Param needCompress
* Whether to compress the LOGO
* @ Throws Exception
*/
Public static void encode (String content, String imgPath, String destPath, boolean needCompress) throws Exception {
BufferedImage image = QRCodeUtil. createImage (content, imgPath, needCompress );
Mkdirs (destPath );
String file = new Random (). nextInt (99999999) + ". jpg ";
ImageIO. write (image, FORMAT_NAME, new File (destPath + "/" + file ));
}

/**
* When the folder does not exist, mkdirs automatically creates a multi-level Directory, which is different from mkdir. (mkdir throws an exception if the parent directory does not exist)
*
* @ Author LongJin
* @ Date 2013-12-11 10:16:36 AM
* @ Param destPath
* Storage directory
*/
Public static void mkdirs (String destPath ){
File file = new File (destPath );
// When the folder does not exist, mkdirs automatically creates a multi-level Directory, which is different from mkdir. (mkdir throws an exception if the parent directory does not exist)
If (! File. exists ()&&! File. isDirectory ()){
File. mkdirs ();
}
}
(4) If you do not need a logo, you only need to pass the logo path to null during the call.

(5) At this point, a QR code generation tool is complete. Of course, someone may need to parse the QR code, so I will write the QR code resolution method here, and it is also convenient for me to view it later.

/**
* Parse the QR code
*
* @ Param file
* QR code Image
* @ Return
* @ Throws Exception
*/
Public static String decode (File 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;
}

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.