生成帶有參數的二維碼,並返回base64碼到前端進行展示

package com.cx.www.cxbl.core.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Hashtable;

public class QRCodeUtil {

    private static final int QRCOLOR = 0xFF000000;   //默認是黑色
    private static final int BGWHITE = 0xFFFFFFFF;   //背景顏色

    /**
     * 生成帶有參數的二維碼,返回base64碼
     * @param contents
     * @param width
     * @param height
     * @return
     */
    public static String creatRrCode(String contents, int width, int height) {
        String binary = null;
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        BitMatrix bitMatrix = null; // 1、讀取文件轉換爲字節數組
        try {
            bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        BufferedImage image = toBufferedImage(bitMatrix);
        //轉換成png格式的IO流
        try {
            ImageIO.write(image, "png", out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = out.toByteArray();
        // 2、將字節數組轉爲二進制
        BASE64Encoder encoder = new BASE64Encoder();
        binary = encoder.encodeBuffer(bytes).trim();
        return binary;
    }

    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.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, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }
 /**
  *測試生成二維碼
  *
  *
  */
    public static void main(String[] args) {
        String binary = QRCodeUtil.creatRrCode("http://www.baidu.com", 200, 200);
        System.out.println(binary);
    }
}

ps:com.google.zxing  jar包地址爲:http://repo1.maven.org/maven2/com/google/zxing/core/3.4.0/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章