图片二维码生产与解析

所需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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值