java implements two-dimensional code, adding logo above the two-dimensional code, adding text below or above the two-dimensional code

Because the company wants to build a warehouse management system, and add or delete inventory through QR code, first look at the display effect of QR code pictures as follows:

Next, import the corresponding jar package,
Link: https://pan.baidu.com/s/1OooqJFUIxWx3p0q0g3AyIA
Extraction code: mdk4
Here's the code

  • 1. Tool class, easy to call

package com.heiniao.pbuy.util.qrcode;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
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.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class QrcodeUtils {

    /**
     * Drawing two-dimensional code
     *
     * @param qrcodePath Store QR code path
     * @param content    QR code content
     * @param height     QR code height
     * @param width      QR code width
     */
    public static void drawQrcode(String qrcodePath, String content, int height, int width) {
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
            //Set UTF-8 to prevent Chinese miscoding
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            //Set the size of the white area around the QR code
            hints.put(EncodeHintType.MARGIN, 1);
            //Set the fault tolerance of QR code
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            //Draw the QR code, remember to call multiFormatWriter.encode() with the hints parameter at the end, otherwise the above settings are invalid
            BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            //qrcFile is used to store generated QR code pictures (no logo, no text)
            File qrcodeFile = QrcodeUtils.findFile(qrcodePath);
            //Start QR code
            MatrixToImageWriter.writeToFile(bitMatrix, "jpg", qrcodeFile);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Add Logo to QR code picture
     *
     * @param qrCodePath QR code path
     * @param logoPath   logo Route
     * @param logoConfig logo configuration file
     */
    public static void addLogoToQRCode(String qrCodePath, String logoPath, String logoQrcodePath, LogoConfig logoConfig) {
        try {
            File qrCodeFile = new File(qrCodePath);
            File logoFile = new File(logoPath);

            if (!qrCodeFile.isFile() || !logoFile.isFile()) {
                System.out.print("file not find origial file !");
                System.exit(0);
            }

            //Read QR code pictures and build drawing objects
            BufferedImage image = ImageIO.read(qrCodeFile);
            Graphics2D g = image.createGraphics();
            //Read logo file
            BufferedImage logo = ImageIO.read(logoFile);
            //Set the location of logo
            int widthLogo = image.getWidth() / logoConfig.getLogoPart();
            int heightLogo = image.getWidth() / logoConfig.getLogoPart(); // Keep the QR code square
            // Calculate picture placement (Center)
            int x = (image.getWidth() - widthLogo) / 2;
            int y = (image.getHeight() - heightLogo) / 2;

            // Start drawing pictures
            g.drawImage(logo, x, y, widthLogo, heightLogo, null);
            g.drawRoundRect(x, y, widthLogo, heightLogo, 10, 10);
            g.setStroke(new BasicStroke(logoConfig.getBorder()));
            g.setColor(logoConfig.getBorderColor());
            g.drawRect(x, y, widthLogo, heightLogo);
            g.dispose();
            ImageIO.write(image, "jpeg", new File(logoQrcodePath));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * @param qrcodePath     QR code path
     * @param textQrcodePath Store text QR code path
     * @param width          Text QR code width
     * @param height         Text QR code height
     * @param qrcodeFontList Text content set
     * @Add text to the QR code
     */
    public static void pressText(String qrcodePath, String textQrcodePath, int width, int height, List<QrcodeFont> qrcodeFontList) {

        try {
            File textQrcodeFile = findFile(qrcodePath);
            System.out.println(textQrcodeFile.length());
            Image src = ImageIO.read(textQrcodeFile);
            int imageW = src.getWidth(null);
            int imageH = src.getHeight(null);
            BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
            Graphics g = image.createGraphics();
            g.setColor(Color.WHITE);//Set brush white
            g.fillRect(0, 0, 600, 600);//Fill the entire screen
            g.drawLine(0, 0, imageW, imageH);
            g.drawImage(src, 100, 150, imageW / 2, imageH / 2, null);
            for (QrcodeFont qrcodeFont : qrcodeFontList) {
                g.setColor(qrcodeFont.getColor());
                g.setFont(new Font("bold", qrcodeFont.getFontStyle(), qrcodeFont.getFontSize()));
                g.drawString(qrcodeFont.getText(), qrcodeFont.getStartX(), qrcodeFont.getStartY());
            }
            g.dispose();

            FileOutputStream out = new FileOutputStream(textQrcodePath);
            ImageIO.write(image, "JPEG", out);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(image);
            out.close();
            System.out.println("image press success");
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    /**
     * @param filepath
     * @return
     * @Find files (create files if none)
     */
    public static File findFile(String filepath) {
        File file = new File(filepath);
        if (!file.exists()) {
            file.mkdir();
        }
        return file;
    }


}
  • 2. Parameter setting entity classes. These are the two entity classes I encapsulate

  1. logo profile

 

package com.heiniao.pbuy.util.qrcode;

import java.awt.Color;

public class LogoConfig {
    // logo default border color
    public static final Color DEFAULT_BORDERCOLOR = Color.WHITE;
    // logo default border width
    public static final int DEFAULT_BORDER = 2;
    // logo size is 1 / 6 of the photo by default
    public static final int DEFAULT_LOGOPART = 6;

    private final int border = DEFAULT_BORDER;
    private final Color borderColor;
    private final int logoPart;

    /**
     * Creates a default config with on color {@link #BLACK} and off color
     * {@link #WHITE}, generating normal black-on-white barcodes.
     */
    public LogoConfig() {
        this(DEFAULT_BORDERCOLOR, DEFAULT_LOGOPART);
    }

    public LogoConfig(Color borderColor, int logoPart) {
        this.borderColor = borderColor;
        this.logoPart = logoPart;
    }

    public Color getBorderColor() {
        return borderColor;
    }

    public int getBorder() {
        return border;
    }

    public int getLogoPart() {
        return logoPart;
    }
}
  1. Set text entity

package com.heiniao.pbuy.util.qrcode;

import java.awt.Color;
import java.awt.Font;

public class QrcodeFont {

    private int startX;//Text display x coordinate
    private int startY;//Text display y coordinate
    private String text;//Text content displayed
    private int fontSize = 30;//font size
    private int fontStyle = Font.BOLD;//font style
    private Color color = Color.BLUE;//Text display color

    public int getStartX() {
        return startX;
    }

    public void setStartX(int startX) {
        this.startX = startX;
    }

    public int getStartY() {
        return startY;
    }

    public void setStartY(int startY) {
        this.startY = startY;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public int getFontSize() {
        return fontSize;
    }

    public void setFontSize(int fontSize) {
        this.fontSize = fontSize;
    }

    public int getFontStyle() {
        return fontStyle;
    }

    public void setFontStyle(int fontStyle) {
        this.fontStyle = fontStyle;
    }

    public Color getColor() {
        return color;
    }

    public void setColor(Color color) {
        this.color = color;
    }

}
  • Finally, write a test class to see the implementation effect

After implementation:

 

 

  1. package com.heiniao.pbuy.util.qrcode;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class QrcodeTest {
        public static final String content = "http://www.baidu.com "; / / contents in QR code
        public static final String logoPath = "d:/logo.jpg";//logo path
    
        public static final String qrcodePath = "D://qrcode.jpg "; / / simple QR code storage address
        public static final String logoQrcodePath = "D://logoQrcode.jpg "; / / with logo QR code storage address
        public static final String textQrcodePath = "D://textQrcode.jpg "; / / there is text and logo QR code storage address
    
        public static void main(String args[]) {
            try {
    
                QrcodeUtils.drawQrcode(qrcodePath, content, 400, 400);
                QrcodeUtils.addLogoToQRCode(qrcodePath, logoPath, logoQrcodePath, new LogoConfig());
    
                //Location of QR code text
                List<QrcodeFont> qrCodeFontList = new ArrayList<QrcodeFont>();
    
                QrcodeFont font1 = new QrcodeFont();
                font1.setStartX(10);
                font1.setStartY(370);
                font1.setText("Warehouse No.: warehouse 4, box 106");
                qrCodeFontList.add(font1);
    
                QrcodeFont font2 = new QrcodeFont();
                font2.setStartX(10);
                font2.setStartY(50);
                font2.setText("Brand: Apple");
                qrCodeFontList.add(font2);
    
                QrcodeFont font3 = new QrcodeFont();
                font3.setStartX(10);
                font3.setStartY(100);
                font3.setText("Model: iPhone XS max");
                qrCodeFontList.add(font3);
    
                QrcodeFont font4 = new QrcodeFont();
                font4.setStartX(10);
                font4.setStartY(150);
                font4.setText("Specification: Black");
                qrCodeFontList.add(font4);
    
                QrcodeUtils.pressText(logoQrcodePath, textQrcodePath, 400, 450, qrCodeFontList);
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    }
    

    The test code is real and effective. I put it on disk d to see the effect:
    Before operation:

Display QR code effect:

 

 

Tags: Java Google QRCode codec

Posted on Sun, 01 Dec 2019 08:45:43 -0800 by lvitup