1.加入依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
2.处理代码,如果是批量处理,需要注意并发问题。
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 lombok.extern.log4j.Log4j2;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Hashtable;
@Log4j2
public class QrCodeGenerator {
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
private static final String FORMAT = "png";
private static final int WIDTH = 200;
private static final int HEIGHT = 200;
public static void generateQrCode(String content, int width, int height, HttpServletResponse response) throws IOException {
BufferedImage image = generateQrCode(content, width, height);
ImageIO.write(image, FORMAT, response.getOutputStream());
}
public static BufferedImage generateQrCode(String content, int width, int height){
width = width == 0 ? WIDTH : width;
height = height == 0 ? HEIGHT : height;
Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.MARGIN, 0);
BitMatrix bitMatrix = null;
try {
bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
} catch (WriterException e) {
e.printStackTrace();
}
return toBufferedImage(bitMatrix);
}
private static BufferedImage toBufferedImage(BitMatrix matrix) {
matrix = removeWhiteEdge(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) ? BLACK : WHITE);
}
}
return image;
}
private static BitMatrix removeWhiteEdge(BitMatrix matrix){
int[] rec = matrix.getEnclosingRectangle();
int resWidth = rec[2];
int resHeight = rec[3];
BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
resMatrix.clear();
for (int i = 0; i < resWidth; i++) {
for (int j = 0; j < resHeight; j++) {
if (matrix.get(i + rec[0], j + rec[1])) {
resMatrix.set(i, j);
}
}
}
return resMatrix;
}
public static void main(String[] args) throws IOException {
BufferedImage image = generateQrCode("http://www.baidu.com", 200, 200);
ImageIO.write(image, FORMAT, new File("C:\\Users\\Administrator\\Desktop\\qrCode.png"));
}
}