java+zxing generates a QR code with logo

java+zxing generates a QR code with logo

Tips before viewing:

The IDEA version used in this article is ultimate 2019.1, and the JDK version is 1.8.0_141.

This article uses the QR code generated by the zxing package, which is a java project managed by Maven, directly upload the code.

pom.xml references part of the code

<dependency>
      <groupId>com.google.zxing</groupId>
      <artifactId>core</artifactId>
      <version>3.4.0</version>
    </dependency>

    <dependency>
      <groupId>com.google.zxing</groupId>
      <artifactId>javase</artifactId>
      <version>3.4.0</version>
    </dependency>

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.9</version>
    </dependency>

Tool class QRCodeUtil.java

package generateQRCode;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;

/**
 * @description 二维码工具类
 * @create 2019-12-18 by jjy
 */
public class QRCodeUtil {
    
    

    private static String CHARACTER = "UTF-8";
    private static String IMAGE_FORMAT = "JPG";
    private static int QRCODE_SIZE = 300;//二维码尺寸
    private static int BLACK = 0xFF000000;//黑色,二维码黑色方块代表1
    private static int WHITE = 0xFFFFFFFF;//白色,二维码白色色方块代表0
    private static int LOGO_SIZE = 60;//logo尺寸

    /**
     * @description 生成二维码
     * @param content
     * @param logoPath
     * @return
     * @throws Exception
     * @create 2019-12-18 by jjy
     */
    private static BufferedImage generateQRCode(String content, String logoPath) throws Exception{
    
    

        Hashtable ht = new Hashtable();
        // 设置二维码纠错等级,L(7%)、M(15%)、Q(25%)、H(30%),纠错等级可存储的信息越少,但对二维码清晰度的要求越小
        ht.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        //设置UTF-8字符编码集
        ht.put(EncodeHintType.CHARACTER_SET, CHARACTER);
        //设置图片边距
        ht.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, ht);

        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        //使用BufferedImage生成二维码图片
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for(int x = 0; x < width; x ++){
    
    
            for (int y = 0; y < height; y++){
    
    
                bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
            }
        }

        //判断是否有logo,没有logo直接生成二维码
        if(StringUtils.isBlank(logoPath)){
    
    
            return bufferedImage;
        }

        //插入logo
        insertLogo(bufferedImage, logoPath);
        return bufferedImage;
    }

    /**
     * @description 插入logo
     * @param bufferedImage
     * @param logoPath
     * @throws Exception
     * @create 2019-12-18 by jjy
     */
     private static void insertLogo(BufferedImage bufferedImage, String logoPath) throws Exception{
    
    

        File file = new File(logoPath);
        if(!file.exists()){
    
    
            System.out.println("logo图片不存在,路径为:" + logoPath);
            return;
        }

        Image logoImage = ImageIO.read(file);
        //插入logo
         Graphics2D graphics2D = bufferedImage.createGraphics();
         int x = (QRCODE_SIZE - LOGO_SIZE)/ 2;
         int y = (QRCODE_SIZE - LOGO_SIZE)/ 2;
         graphics2D.drawImage(logoImage, x, y,LOGO_SIZE, LOGO_SIZE, null);
         Shape shape = new RoundRectangle2D.Float(x, y, LOGO_SIZE, LOGO_SIZE, 6, 6);
         graphics2D.setStroke(new BasicStroke(3f));
         graphics2D.draw(shape);
         graphics2D.dispose();
     }

    /**
     * @description 生成二维码并保存图片
     * @param content
     * @param logoPath
     * @param outPath
     * @throws Exception
     * @create 2019-12-18 by jjy
     */
     public static void encode(String content, String logoPath, String outPath) throws Exception {
    
    
        BufferedImage bufferedImage = generateQRCode(content, logoPath);
        File file = new File(outPath);
        if(!file.exists()){
    
    
            file.mkdirs();
        }
        String QRCodeName = System.currentTimeMillis() + ".jpg";
        ImageIO.write(bufferedImage, IMAGE_FORMAT, new File(outPath + File.separator + QRCodeName));
     }

    /**
     * @description 解析二维码内容
     * @param QRCodePath
     * @return
     * @throws Exception
     * @create 2019-12-18 by jjy
     */
     public static String decode(String QRCodePath) throws Exception {
    
    
         File file = new File(QRCodePath);
         if(!file.exists()){
    
    
             System.out.println("二维码路径不正确,路径为:" + QRCodePath);
             return null;
         }
         BufferedImage bufferedImage = ImageIO.read(file);
         BufferedImageLuminanceSource bufferedImageLuminanceSource = new BufferedImageLuminanceSource(bufferedImage);
         BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(bufferedImageLuminanceSource));
         Hashtable hint = new Hashtable();
         hint.put(DecodeHintType.CHARACTER_SET, CHARACTER);
         Result result = new MultiFormatReader().decode(binaryBitmap, hint);
         return result.getText();
     }
}

Test class Test.java

package generateQRCode;

public class Test {
    
    
    public static void main(String[] args) throws Exception{
    
    
        String content = "https://blog.csdn.net/weixin_43611145";
        String logoPath = "C:\\Users\\jjy\\Desktop\\微信图片_20191218094620.jpg";
        String outPath = "D:/QRCode";
        QRCodeUtil.encode(content, logoPath, outPath);

        String QRCodePath = "D:\\QRCode\\1.jpg";
        System.out.println(QRCodeUtil.decode(QRCodePath));
    }
}

The results are as follows
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43611145/article/details/103599522