Java实现生成带logo的二维码

废话不多说,开门见山,使用google的zxing包实现生成二维码。

下面直接贴代码:
首先pom文件导入zxing包

       
            com.google.zxing
            javase
            3.3.3
        

接下来就是实现代码了

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

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

/**
 * 二维码相关
 * @author Joaz
 *
 */
public class QRCodeDome {

    /**
     * 创建二维码图片
     *
     * @param content    二维码携带信息
     * @param qrCodeSize 二维码图片大小
     * @param filePath   生成的二维码图片的保存的路径
     */
    public static void createQrCodeImage(String content, int qrCodeSize, String filePath) {
        try {
            BufferedImage bi = createQrCode(content, qrCodeSize);
            File imgFile = new File(filePath);
            ImageIO.write(bi, "JPEG", imgFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成包含字符串信息的二维码图片
     *
     * @param content    二维码携带信息
     * @param qrCodeSize 二维码图片大小
     */
    private static BufferedImage createQrCode(String content, int qrCodeSize) {
        try {
            // 设置二维码纠错级别Map
            Hashtable hintMap = new Hashtable<>();
            // 矫错级别
            hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            // 创建比特矩阵(位矩阵)的QR码编码的字符串
            BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap);
            // 使BufferedImage勾画QRCode  (matrixWidth 是行二维码像素点)
            int matrixWidth = byteMatrix.getWidth();
            int matrixHeight = byteMatrix.getWidth();
            BufferedImage image = new BufferedImage(matrixWidth - 65, matrixWidth - 65, BufferedImage.TYPE_INT_RGB);
            image.createGraphics();
            Graphics2D graphics = (Graphics2D) image.getGraphics();
            graphics.setColor(Color.WHITE);
            graphics.fillRect(0, 0, matrixWidth, matrixHeight);
            // 使用比特矩阵画并保存图像
            graphics.setColor(Color.BLACK);
            for (int i = 0; i < matrixWidth; i++) {
                for (int j = 0; j < matrixWidth; j++) {
                    if (byteMatrix.get(i, j)) {
                        graphics.fillRect(i - 33, j - 33, 2, 2);
                    }
                }
            }
            return image;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static final String CHARSET = "UTF-8";


    /**
     * 创建二维码图片
     * @param contents 二维码携带信息
     * @param width    宽度
     * @param height   高度
     * @param qrFile   二维码保存的路径
     * @return
     */
    public static File encode(String contents, int width, int height, File qrFile) {
        //生成条形码时的一些配置
        Map hints = new HashMap<>();
        // 指定纠错等级,纠错级别(L 7%、M 15%、Q 25%、H 30%)
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 内容所使用字符集编码
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);

        BitMatrix bitMatrix;
        try (OutputStream out = new FileOutputStream(qrFile)){
            // 生成二维码
            bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
            MatrixToImageWriter.writeToStream(bitMatrix, "png", out);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return qrFile;
    }


    /**
     * 二维码图片组合logo图片
     * @param qrFile        二维码图片文件
     * @param logoFile      logo图片
     * @param newQrFile     组合后带logo的二维码图片
     * @return
     */
    public static File encodeWithLogo(File qrFile, File logoFile, File newQrFile) {
        //OutputStream os = null ;
        try (OutputStream os = new FileOutputStream(newQrFile)){
            Image image2 = ImageIO.read(qrFile) ;
            int width = image2.getWidth(null) ;
            int height = image2.getHeight(null) ;
            BufferedImage bufferImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB) ;
            //BufferedImage bufferImage =ImageIO.read(image) ;
            Graphics2D g2 = bufferImage.createGraphics();
            g2.drawImage(image2, 0, 0, width, height, null) ;
            int matrixWidth = bufferImage.getWidth();
            int matrixHeigh = bufferImage.getHeight();

            //读取Logo图片
            BufferedImage logo= ImageIO.read(logoFile);
            //开始绘制图片
            g2.drawImage(logo,matrixWidth/5*2,matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5, null);//绘制
            BasicStroke stroke = new BasicStroke(10,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
            g2.setStroke(stroke);// 设置笔画对象
            //指定弧度的圆角矩形
            RoundRectangle2D.Float round = new RoundRectangle2D.Float(matrixWidth/5*2, matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5,20,20);
            g2.setColor(Color.white);
            g2.draw(round);// 绘制圆弧矩形

            //设置logo 有一道灰色边框
            BasicStroke stroke2 = new BasicStroke(1,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
            g2.setStroke(stroke2);// 设置笔画对象
            RoundRectangle2D.Float round2 = new RoundRectangle2D.Float(matrixWidth/5*2+2, matrixHeigh/5*2+2, matrixWidth/5-4, matrixHeigh/5-4,20,20);
            g2.setColor(new Color(128,128,128));
            g2.draw(round2);// 绘制圆弧矩形

            g2.dispose();

            bufferImage.flush() ;
            //os = new FileOutputStream(newQrFile) ;
            JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os) ;
            en.encode(bufferImage) ;

        } catch (Exception e) {
            e.printStackTrace();
        } /*finally {
            if(os!=null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }*/
        return newQrFile ;
    }








    public static void main(String[] args) throws Exception {
        // 需要二维码携带的内容
        String content = "http://192.168.3.228:8686/demo/user/analyzeQRCode";
        // 生成二维码的大小
        int qrCodeSize = 400;
        // 将二维码保存的路径
        String filePath = "E:/img/testQRImage3.jpg";
        String newFilePath = "E:/img/testQRImage4.jpg";

        // 执行方法,生成二维码
        //createQrCodeImage(content, qrCodeSize, filePath);

        // 执行方法,生成二维码
        File encode = encode(content, qrCodeSize, qrCodeSize, new File(filePath));
        // 已生成的二维码组合logo
        encodeWithLogo(encode,new File("C:/Users/ad/Desktop/测试2.png"),new File(newFilePath));
    }

}

希望能对有需要的人有帮助,路过的点个赞吧!

你可能感兴趣的:(Java实现生成带logo的二维码)