maven
1 <dependency> 2 <groupId>com.google.zxing</groupId> 3 <artifactId>core</artifactId> 4 <version>3.3.3</version> 5 </dependency>
代码
import com.google.zxing.BarcodeFormat;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.junit.Test;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
// 测试二维码生成
public class QrCodeTest {
@Test
public void testGenerate() throws Exception {
QRCodeWriter writer = new QRCodeWriter();
int width = 400;
int height = 400;
BitMatrix bitMatrix = writer.encode("http://www.baidu.com", BarcodeFormat.QR_CODE, width, height);
BufferedImage image = new BufferedImage(bitMatrix.getWidth(), bitMatrix.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
image.setRGB(i,j, bitMatrix.get(i,j) ? Color.BLACK.getRGB(): Color.white.getRGB());
}
}
File file = new File("./test.jpg");
System.out.println(file.getAbsolutePath());
ImageIO.write(image, "jpg", file);
}
}
如果中文乱码,可以先把待处理的内容做一次URLEncoder,变成没有汉字的内容再去调用方法就可以了。
原文:https://www.cnblogs.com/zhangyy3/p/9218909.html