简单介绍一下使用google的zxing实现将内容生成为二维码,通过扫码得到。
1.需要用到的依赖如下:
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
2.代码实现:
/**
*
* @param content 需要生成的内容
* @param outPath 生成的路径
* @return
*/
public static String createCode(String content,String outPath){
int width = 1200;
int height = 1200;
String format = "png";
System.out.println(content.length());
// 定义二维码参数
HashMap hints = new HashMap();
// 字符集
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 纠错级别
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
// 空白
hints.put(EncodeHintType.MARGIN, 2);
if(content.length()>1800){
return null;
}
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, width, height, hints);
Path file = new File(outPath).toPath();
MatrixToImageWriter.writeToPath(bitMatrix, format, file);
return outPath;
} catch (Exception e) {
return null;
}
}
3. 测试:
public static void main(String[] args) {
createCode("hello,world!","d:\\H.png");
}
4.生成效果:
此处为设定地址path下的二维码,便不贴图了