所需jar包
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.0.0</version>
</dependency>
生产二维码图像代码:
/**
* 生成图像
* @param content jsonStr
* @throws WriterException
* @throws IOException
*/
public static String testContentEncode(String content) throws IOException {
int width = 200; // 图像宽度
int height = 200; // 图像高度
String format = "png";// 图像类型
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
ByteArrayOutputStream os = null;
try {
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
// 生成矩阵
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE, width, height, hints);
BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
os = new ByteArrayOutputStream();
ImageIO.write(image, format, os);
InputStream is = new ByteArrayInputStream(os.toByteArray());//获取输入流
String path = FileManager.upload(null, format, is);
return path;
}catch (Exception e){
LOGGER.info("上传二维码失败, 原因:{}", e.getMessage());
e.printStackTrace();
}finally {
if(os != null){
os.close();
}
}
LOGGER.info("上传二维码成功");
return null;
}
解析图像代码:
/**
* 解析图像
* @param url 图像url
*/
public static Result analysisImageUrl(String url) {
BufferedImage image;
try {
// image = ImageIO.read(new File(url));
image = ImageIO.read(new URL(url));
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Map<DecodeHintType, Object> hintMap = new HashMap<DecodeHintType, Object>();
hintMap.put(DecodeHintType.CHARACTER_SET, "UTF-8");
// 对图像进行解码
Result result = new MultiFormatReader().decode(binaryBitmap, hintMap);
System.out.println("图片中内容: ");
System.out.println(result.toString());
return result;
} catch (IOException e) {
e.printStackTrace();
} catch (NotFoundException e) {
e.printStackTrace();
}
return null;
}