java把字符串生成二维码

无敌的宇宙
无敌的宇宙
擅长邻域:Java,HTML,JavaScript,MySQL,支付,退款,图片上传

分类: Java 标签: java把字符串生成二维码 字符串生成二维码 字符串生成二维码代码 java把文字生成二维码

2020-10-15 19:23:46 1168浏览

java把字符串生成二维码,1.pom加入的依赖,下载需要的jar包;2.新建工具类
1.pom加入的依赖
 <dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
2.新建工具类
public class QRcodeImageUtil {

private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;

/**
* 根据字符串生成对应的二维码图片png
* 大小:200*200
*
* content:要转换的内容
* path:生成的二维码图片的绝对路径
* filename: 生成的文件名
*/
public static void buildQuickMark(String content, String path, String filename) throws Exception {
try {
BitMatrix byteMatrix = new MultiFormatWriter().encode(new String(content.getBytes(), "iso-8859-1"),
BarcodeFormat.QR_CODE, 200, 200);
String format = "png";
File file = new File(path+"\\"+filename+"."+format);
BufferedImage image = toBufferedImage(byteMatrix);
if (!ImageIO.write(image, format, file)) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
} catch (Exception e) {
e.printStackTrace();
}
}

private static BufferedImage toBufferedImage(BitMatrix 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;
}
3.示例代码
public static void main(String[] args) throws Exception {
String content = "你好,二维码";
String path = "D:\\folder1\\temp";
String filename = "test";
QRcodeImageUtil .buildQuickMark(content, path, filename);
System.out.println("done");
}

好博客就要一起分享哦!分享海报

此处可发布评论

评论(0展开评论

暂无评论,快来写一下吧

展开评论

您可能感兴趣的博客

客服QQ 1913284695