二维码生成工具包
package com.dhsr.springboot_code.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.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Hashtable;
public class QrCodeCreateUtil {
public static boolean createQrCode(OutputStream outputStream, String content, int qrCodeSize, String imageFormat) throws WriterException, IOException {
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap);
int matrixWidth = byteMatrix.getWidth();
int revise = matrixWidth * 2 / 9;
BufferedImage image = new BufferedImage(matrixWidth - revise, matrixWidth - revise, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, matrixWidth, matrixWidth);
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 - revise / 2, j - revise / 2, 1, 1);
}
}
}
return ImageIO.write(image, imageFormat, outputStream);
}
public static String readQrCode(InputStream inputStream) throws IOException {
BufferedImage image = ImageIO.read(inputStream);
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
QRCodeReader reader = new QRCodeReader();
Result result = null;
try {
result = reader.decode(bitmap);
} catch (ReaderException e) {
e.printStackTrace();
}
return result.getText();
}
public static void main(String[] args) throws IOException, WriterException {
String content = "http://baidu.com";
String path = "E:\\Project_job\\springboot_code\\src\\main\\resources\\img\\test.jpg";
createQrCode(new FileOutputStream(new File(path)), content, 90, "JPEG");
String info = readQrCode(new FileInputStream(new File(path)));
System.out.println(info);
}
}