All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.yixan.tools.common.util.QrCode Maven / Gradle / Ivy

There is a newer version: 3.7.1
Show newest version
package com.yixan.tools.common.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Hashtable;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
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;

/**
 * 二维码工具
 *
 * @author zhh
 * @version V1.0 2017年3月8日
 */
public abstract class QrCode {

    /**
     * 生成二维码
     * 
     * @param content 内容
     * @param size 尺寸
     * @param os 输出流
     */
    public static void generate(String content, int size, OutputStream os) {
        generate(content, size, Math.max(5, size / 10), os);
    }

    /**
     * 生成二维码
     * 
     * @param content 内容
     * @param size 尺寸
     * @param margin 边距
     * @param os 输出流
     */
    public static void generate(String content, int size, int margin, OutputStream os) {
        try {
            Hashtable hints = new Hashtable();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF8");

            QRCodeWriter writer = new QRCodeWriter();

            // 生成二维码
            BitMatrix matrix = writer.encode(content, BarcodeFormat.QR_CODE, size, size, hints);

            // 重设白边大小
            if (margin >= 0) {
                matrix = updateBit(matrix, margin);
            }

            MatrixToImageWriter.writeToStream(matrix, "png", os);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 重设白边框宽度
     * 
     * @param matrix
     * @param margin
     * @return
     */
    private static BitMatrix updateBit(BitMatrix matrix, int margin) {
        int m = margin * 2;
        int[] rectangle = matrix.getEnclosingRectangle(); // 获取二维码图案的属性
        int w = rectangle[2] + m;
        int h = rectangle[3] + m;
        BitMatrix result = new BitMatrix(w, h); // 按照自定义边框生成新的BitMatrix
        result.clear();
        for (int i = margin; i < w - margin; i++) { // 循环,将二维码图案绘制到新的bitMatrix中
            for (int j = margin; j < h - margin; j++) {
                if (matrix.get(i - margin + rectangle[0], j - margin + rectangle[1])) {
                    result.set(i, j);
                }
            }
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        String content = "http://www.baidu.com";
        int size = 100;
        try (OutputStream os = new FileOutputStream(new File("D:/baidu." + size + ".png"))) {
            QrCode.generate(content, size, os);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy