package com.ruoyi.other.util;
|
|
import com.google.zxing.BarcodeFormat;
|
import com.google.zxing.EncodeHintType;
|
import com.google.zxing.MultiFormatWriter;
|
import com.google.zxing.common.BitMatrix;
|
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
|
|
import javax.imageio.ImageIO;
|
import java.awt.image.BufferedImage;
|
import java.io.OutputStream;
|
import java.util.Hashtable;
|
|
public class QRCodeUtils {
|
|
private static final String CHARSET = "utf-8";
|
private static final String FORMAT_NAME = "JPG";
|
private static final int QRCODE_SIZE = 300;
|
|
private QRCodeUtils() {
|
}
|
|
public static void encode(String content, OutputStream output) throws Exception {
|
Hashtable<EncodeHintType, Object> 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
|
);
|
BufferedImage image = new BufferedImage(QRCODE_SIZE, QRCODE_SIZE, BufferedImage.TYPE_INT_RGB);
|
for (int x = 0; x < QRCODE_SIZE; x++) {
|
for (int y = 0; y < QRCODE_SIZE; y++) {
|
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
|
}
|
}
|
ImageIO.write(image, FORMAT_NAME, output);
|
}
|
}
|