Categories
Uncategorized

Use Spring Boot + zxing, generate two-dimensional code can be so simple

In web development, often encounter a situation you want to generate two-dimensional code, such as to pay for the use of micro-channel, web sign-on, we share an example of a two-dimensional code generation Boot Spring, here uses google’s zxing tools.

Article directory

I. Introduction two-dimensional code, the two-dimensional code to code generation introduced jar package 1. 2. 3. write tools write control layer 4. Run the code and view the results

A two-dimensional code Description

Two-dimensional code, also known as QR Code, QR stands for Quick Response, it is the ultra-popular one device encoding a move in recent years.

Two-dimensional code image memo data symbols are black and white with a specific geometry according to certain rules in a plane (two-dimensional direction) distribution.

The main scenarios are as follows:

    Access to information (business cards, maps, WIFI password, data)

    Website Jump (Jump to microblogging, mobile site, site)

    Advertising push (user scan code, browse the merchant directly push video, audio advertising)

    Phone electricity supplier (user scan code, phone directly under the shopping list)

    Anti-counterfeiting traceability (user scan code to see the producer; while the background can obtain final consumption)

    Promotions (user scan code, download e-coupons, sweepstakes)

    Member Management (members access to electronic information, VIP service on the user’s mobile phone)

    Mobile payment (two-dimensional code scanning merchandise, through a bank or third-party payment channels provided by the mobile terminal to complete the payment)

    Account login (two-dimensional code scanning to sign individual sites or software)

Second, write code to generate two-dimensional code

1. Introducing a jar package

pom.xml introduced zxing jar package.


<dependency>
    <groupId>com.google.zxinggroupId>
    <artifactId>coreartifactId>
    <version>3.2.0version>
dependency>
<dependency>
    <groupId>com.google.zxinggroupId>
    <artifactId>javaseartifactId>
    <version>3.2.0version>
dependency>

2. Writing Tools

QRCodeUtil.java code is as follows:

/ ** * QRCodeUtil dimensional code generation tools * /


public class QRCodeUtil {

    private static final String CHARSET = "utf-8";
    private static final String FORMAT_NAME = "JPG";
    

// size two-dimensional code


    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 {
        Hashtable hints = new Hashtable();
        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;
    }

    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) { 

// compression 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, 00null); 

// draw the map after narrowing


            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, 66);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        mkdirs(destPath);
        ImageIO.write(image, FORMAT_NAME, new File(destPath));
    }

    public static BufferedImage encode(String content, String imgPath, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        return image;
    }

    public static void mkdirs(String destPath) {
        File file = new File(destPath);
        

// When the folder does not exist, mkdirs will automatically create several directory different from the mkdir. (Mkdir if the parent directory does not exist it will throw an exception)


        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }

    public static void encode(String content, String imgPath, OutputStream output, boolean needCompress)
            throws Exception 
{
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        ImageIO.write(image, FORMAT_NAME, output);
    }

    public static void encode(String content, OutputStream output) throws Exception {
        QRCodeUtil.encode(content, null, output, false);
    }
}

3. The write control layer Code

QrCodeController.java code is as follows:

    

/ ** * normal two-dimensional code according to the generated URL * /


    @RequestMapping(value = "/createCommonQRCode")
    public void createCommonQRCode(HttpServletResponse response, String url) throws Exception {
        ServletOutputStream stream = null;
        try {
            stream = response.getOutputStream();
            

// use the tools to generate two-dimensional code


            QRCodeUtil.encode(url, stream);
        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            if (stream != null) {
                stream.flush();
                stream.close();
            }
        }
    }

    

/ ** * logo generate two-dimensional code in accordance with the URL * /


    @RequestMapping(value = "/createLogoQRCode")
    public void createLogoQRCode(HttpServletResponse response, String url) throws Exception {
        ServletOutputStream stream = null;
        try {
            stream = response.getOutputStream();
            String logoPath = Thread.currentThread().getContextClassLoader().getResource("").getPath() 
                    + "templates" + File.separator + "logo.jpg";
            

// use the tools to generate two-dimensional code


            QRCodeUtil.encode(url, logoPath, stream, true);
        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            if (stream != null) {
                stream.flush();
                stream.close();
            }
        }
    }

4. Run and view the results

This project provides a common two-dimensional code generation and two interfaces, the project started with a logo of two-dimensional code, two-dimensional code http://www.baidu.com us to demonstrate at this url next generation;

    Ordinary two-dimensional code to generate a local browser to open http: // localhost:? 8080 / createCommonQRCode url = http: //www.baidu.com, generate two-dimensional code shots are as follows:


Baidu’s ordinary two-dimensional code generation

    Two-dimensional code generated with the logo of a local browser to open http: // localhost: 8080 / createLogoQRCode url = http:? //Www.baidu.com, generate two-dimensional code shots are as follows:


Generating a two-dimensional code logo with Baidu

This Spring Boot 2.X in use ZXing to generate two-dimensional code to achieve full functionality, there are questions please leave a message to communicate Oh! Complete Source Address: https://github.com/suisui2019/springboot-study

Recommended Reading

1. Under analysis from a technical perspective Why do not send “artwork” on the Internet 2.Spring Boot 2.X how to quickly integrate jpa? 3.Spring Boot of Profile– quickly get multi-use environment with integrated switch 4.Spring Boot 2.X Spring-cache, make your website speed fly 5. Use Spring Boot + WxJava achieve integrated micro believe the site login feature


Limited Time receive a free Java-related information, covering Java, Redis, MongoDB, MySQL, Zookeeper, Spring Cloud, Dubbo / Kafka, Hadoop, Hbase, Flink high concurrent distributed, big data and machine learning techniques. Watch below the number to receive a free public:

 

Leave a Reply