In the era of mobile Internet, various activity scanning codes and payment codes based on mobile terminals emerge endlessly. So how do we generate the QR code we want in Java? The following is about using Google. Zxing to generate two-dimensional code in Java development.


In general, Java generation of two-dimensional code there are three ways, one is based on Google. Zxing, is the Company of Google; One is based on Jp.Sourceforge. Qrcode, a Japanese company; There is also a jquery plugin based on jquery.qrcode.js. More commonly used is the way of Google. Zxing, here we take it as an example to explain how to generate two-dimensional code.

1. Use Maven version control

Using Maven to control the version here, if you want to view the latest version used, can go to http://maven.aliyun.com/nexus/#nexus-search; Quick ~zxing The example version is 3.3.0, quoted as follows:

<dependency>
	<groupId>com.google.zxing</groupId>
	<artifactId>javase</artifactId>
	<version>3.3.0</version>
</dependency>
Copy the code

2, generate/decode two-dimensional code tool class

A utility class for generating qr codes has been packaged below for your reference:

package com.yclimb.zxing; import com.alibaba.fastjson.JSONObject; import com.google.zxing.*; 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 org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; /** * @author yclimb * @date 2018/4/23 */ public class QRCodeUtil {private static Loggerlog= LoggerFactory.getLogger(QRCodeUtil.class); /** * generate a qr code * @param text content, Public static void encodeQRCode(String text, String path) {public static void encodeQRCode(String text, String path) {encodeQRCode(text, path, null, null, null); @param path @param width @param height @param width @param height Default 300 * @param format generated two-dimensional code format, Public static void encodeQRCode(String text, String path, Integer width, Integer height, String format) {try {// Get File object File = new File(path); // Check whether the directory where the target file resides existsif(! File.getparentfile ().exists()) {// If the directory where the target file resides does not exist, create a parent directory log.info("Destination file directory does not exist, ready to create it!");
                if(! file.getParentFile().mkdirs()) { log.info("Failed to create target file directory!");
                    return; }} / / wideif(width == null) { width = 300; } / / highif(height == null) { height = 300; } // Image formatif (format == null) {
                format = "png"; } // Set character set encoding Map<EncodeHintType, Object> hints = new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET,"UTF-8"); BitMatrix = new MultiFormatWriter().encode(text, barcodeformat.qr_code, width, height, hints); Path outputPath = paths.get (Path); / / write file MatrixToImageWriter. WriteToPath (bitMatrix, format, outputPath); } catch (Exception e) { log.error(e.getMessage(), e); }} /** * Decode the two-dimensional code picture * @param filePath two-dimensional code path * @returnPublic static JSONObject decodeQRCode(String filePath) {try {BufferedImage image = imageio.read (new) File(filePath)); // Multistep parse LuminanceSourcesource = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source); BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer); / / one pace reachs the designated position / / BinaryBitmap BinaryBitmap = new BinaryBitmap (new HybridBinarizer (new BufferedImageLuminanceSource (image))) / / Set character encoding Map<DecodeHintType, String> Hints = new HashMap<>(); hints.put(DecodeHintType.CHARACTER_SET,"UTF-8"); Result Result = new MultiFormatReader().decode(binaryBitmap, hints); JSONObject content = jsonObject.parseObject (result.gettext ()); System.out.println("Picture content:");
            System.out.println(Content: "" + content.toJSONString());
            System.out.println("Format in picture:");
            System.out.println("The encode." + result.getBarcodeFormat());

            return content;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        returnnull; }}Copy the code

3. Test method

Public static void main(String[] args) {// Generate path String filePath ="/Users/yclimb/Documents/tmp/first.png"; EncodeQRCode ("The first QR code", filePath); // decodeQRCode(filePath); }Copy the code

conclusion

To this article is over, pay attention to the public account to view more push!!