java二維碼生成

1、導(dǎo)入maven依賴

 <!--二維碼工具包-->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.0</version>
        </dependency>

2. QrCodeUtil工具類

package com.futurehotel.cik.biz.util;

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 lombok.Cleanup;

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

/**
 * 二維碼工具類
 */
public class QrCodeUtil {

    private static final String CHARSET = "utf-8";
    private static final String FORMAT_NAME = "JPG";
    // 二維碼尺寸
    private static final int QRCODE_SIZE = 300;
    // LOGO寬度
    private static final int WIDTH = 60;
    // LOGO高度
    private static final int HEIGHT = 60;


    /**
     * @param content      二維碼內(nèi)容
     * @param logoStream   logo的文件流,不需要就傳null
     * @param qrCodeStream 二維碼輸出文件流
     * @param needCompress logo圖片是否需要壓縮
     * @throws Exception
     */
    public static void createImage(String content, InputStream logoStream,
                                   OutputStream qrCodeStream, boolean needCompress) throws Exception {
        createImage(content, logoStream, qrCodeStream, FORMAT_NAME, needCompress);
    }

    /**
     * @param content      二維碼內(nèi)容
     * @param logoStream   logo的文件流,不需要就傳null
     * @param qrCodeStream 二維碼輸出文件流
     * @param formatName   二維碼圖片格式
     * @param needCompress logo圖片是否需要壓縮
     * @throws Exception
     */
    public static void createImage(String content, InputStream logoStream, OutputStream qrCodeStream,
                                   String formatName, 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);
            }
        }
        // 插入圖片
        QrCodeUtil.insertImage(image, logoStream, needCompress);
        //輸出到輸出流
        ImageIO.write(image, formatName, qrCodeStream);
    }

    private static void insertImage(BufferedImage source, InputStream logoStream, boolean needCompress) throws Exception {
        if (logoStream == null) {
            return;
        }
        Image src = ImageIO.read(logoStream);
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) { // 壓縮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, 0, 0, null); // 繪制縮小后的圖
            g.dispose();
            src = image;
        }
        // 插入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, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    public static String decode(InputStream inputStream) throws Exception {
        BufferedImage image = ImageIO.read(inputStream);
        if (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable hints = new Hashtable();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        result = new MultiFormatReader().decode(bitmap, hints);
        return result.getText();
    }

    public static void main(String[] args) throws Exception {
        // 存放在二維碼中的內(nèi)容
        String text = "我是小銘";
        // 嵌入的logo文件流
        @Cleanup InputStream logoStream = new FileInputStream("D:\\bai.jpg");
        // 輸出二維碼的文件流
        @Cleanup FileOutputStream qrCodeOutputStream = new FileOutputStream("D:\\bai_two.jpg");
        //生成二維碼
        QrCodeUtil.createImage(text, logoStream, qrCodeOutputStream, true);
        qrCodeOutputStream.flush();
        // 解析二維碼
        @Cleanup InputStream qrCodeInputStream = new FileInputStream("D:\\bai_two.jpg");
        String str = QrCodeUtil.decode(qrCodeInputStream);
        // 打印出解析出的內(nèi)容
        System.out.println(str);
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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