Java實現(xiàn)生成帶logo的二維碼

廢話不多說,開門見山,使用google的zxing包實現(xiàn)生成二維碼。

下面直接貼代碼:
首先pom文件導(dǎo)入zxing包

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

接下來就是實現(xiàn)代碼了

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;

/**
 * 二維碼相關(guān)
 * @author Joaz
 *
 */
public class QRCodeDome {

    /**
     * 創(chuàng)建二維碼圖片
     *
     * @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 {
            // 設(shè)置二維碼糾錯級別Map
            Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<>();
            // 矯錯級別
            hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            // 創(chuàng)建比特矩陣(位矩陣)的QR碼編碼的字符串
            BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap);
            // 使BufferedImage勾畫QRCode  (matrixWidth 是行二維碼像素點(diǎn))
            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";


    /**
     * 創(chuàng)建二維碼圖片
     * @param contents 二維碼攜帶信息
     * @param width    寬度
     * @param height   高度
     * @param qrFile   二維碼保存的路徑
     * @return
     */
    public static File encode(String contents, int width, int height, File qrFile) {
        //生成條形碼時的一些配置
        Map<EncodeHintType, Object> hints = new HashMap<>();
        // 指定糾錯等級,糾錯級別(L 7%、M 15%、Q 25%、H 30%)
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 內(nèi)容所使用字符集編碼
        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);// 設(shè)置筆畫對象
            //指定弧度的圓角矩形
            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);// 繪制圓弧矩形

            //設(shè)置logo 有一道灰色邊框
            BasicStroke stroke2 = new BasicStroke(1,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
            g2.setStroke(stroke2);// 設(shè)置筆畫對象
            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 {
        // 需要二維碼攜帶的內(nèi)容
        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";

        // 執(zhí)行方法,生成二維碼
        //createQrCodeImage(content, qrCodeSize, filePath);

        // 執(zhí)行方法,生成二維碼
        File encode = encode(content, qrCodeSize, qrCodeSize, new File(filePath));
        // 已生成的二維碼組合logo
        encodeWithLogo(encode,new File("C:/Users/ad/Desktop/測試2.png"),new File(newFilePath));
    }

}

希望能對有需要的人有幫助,路過的點(diǎn)個贊吧!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容