1、添加依赖
<!--google生成二维码依赖-->
<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、创建工具类
public class QRCodeUtil {
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
public static void zxingCodeCreate(String text, int width, int height, String outPutPath, String imageType) throws UnsupportedEncodingException {
Map<EncodeHintType, String> his = new HashMap<EncodeHintType, String>();
his.put(EncodeHintType.CHARACTER_SET, "utf-8");
text = new String(text.getBytes("UTF-8"),"UTF-8");
try {
BitMatrix encode = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height,his);
int codeWidth = encode.getWidth();
int codeHeight = encode.getHeight();
BufferedImage image = new BufferedImage(codeWidth, codeHeight, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < codeWidth; i++) {
for (int j = 0; j < codeHeight; j++) {
image.setRGB(i, j, encode.get(i, j) ? BLACK : WHITE);
}
}
File outPutImage = new File(outPutPath);
if (!outPutImage.exists())
outPutImage.createNewFile();
ImageIO.write(image, imageType, outPutImage);
} catch (WriterException e) {
e.printStackTrace();
System.out.println("二维码生成失败");
} catch (IOException e) {
e.printStackTrace();
System.out.println("生成二维码图片失败");
}
}
}
3、编写测试类
public class Test{
@Test
public void test(){
QRCodeUtil.zxingCodeCreate("我使用Java生成了二维码",300, 300, "E:/borths.jpg", "jpg");
}
}
4、生成二维码测试
5、效果展示