一、首先在maven中添加一下jar包
代码语言:javascript复制<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
然后新建个工具类 QrcodeUtil
代码语言:javascript复制// 图片宽度的一半
private static final int width = 500;
private static final int height = 500;
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
//生成二维码存放路径
private static final String destImagePath="d:\qrcode.jpg";
//扫描二维码跳转页面
private static final String content="http://www.baidu.com";
// 二维码写码器
private static MultiFormatWriter multiWriter = new MultiFormatWriter();
代码语言:javascript复制/**
* 生成二维码
*
* @param content 要生成二维码的内容
* @param width 二维码的宽度
* @param height 二维码的高
* @param destImagePath 生成二维码图片的路径
* @return 是否生成成功
*/
public static boolean encode(String content, int width, int height, String destImagePath) {
try {
long startTime = System.currentTimeMillis();
File destImagePaths = new File(destImagePath);
//生成二维码图片文件(不带LOGO)
ImageIO.write(genQrcode(content, width, height), "jpg",destImagePaths );
System.out.println("生成成功!");
System.out.println("耗时: " (System.currentTimeMillis()-startTime)/1000.0 "s");
System.out.println("生成文件路径: " destImagePaths.getAbsolutePath());
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
代码语言:javascript复制/**
* 生成二维码图片文件(不带LOGO)
*
* @param content 要生成二维码的内容
* @param width 二维码的高度
* @param height 二维码的宽度
* @return 二维码图片
* @throws WriterException 异常
*/
private static BufferedImage genQrcode(String content, int width, int height) throws WriterException {
Map<EncodeHintType, String> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//根据高度和宽度生成像素矩阵
BitMatrix bitMatrix = multiWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
BufferedImage image = new BufferedImage(bitMatrix.getWidth(), bitMatrix.getHeight(), BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < bitMatrix.getWidth(); x ) {
for (int y = 0; y < bitMatrix.getHeight(); y ) {
//填充黑白两色
image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
}
}
return image;
}
main方法
代码语言:javascript复制public static void main(String[] args) {
// 依次为内容,宽,长,储存路径
QrcodeUtil.encode(content, width, height, destImagePath);
}