Java二维码生成工具类

依赖

<!-- 二维码生成包 -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.2.0</version>
</dependency>

工具类

/**
 * 二维码生成工具类
 */
public class QrCodeUtil {
	
	/**
     * 生成二维码
     * David
     * @param url  url 网址
     * @param width     二维码宽度
     * @param height    二维码高度
     * @param imgPath   生成的二维码url: 路径+文件名
     */
    public static void encode(String url, int width, int height, String imgPath) {
 
        Map<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
 
        // 指定纠错等级
 
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
 
        // 指定编码格式
 
        hints.put(EncodeHintType.CHARACTER_SET, "UTF8");
 
        try {
 
            BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height, hints);
 
            MatrixToImageWriter.writeToStream(bitMatrix, "png", new FileOutputStream(imgPath));
 
//            MatrixToImageWriter.writeToStream(bitMatrix, "png", response.getOutputStream());// 输出图像
 
 
        } catch (Exception e) {
 
            e.printStackTrace();
 
        }
 
    }
 
    /**
     * 二维码解析
     * @param imgPath   二维码图片 路径+文件名
     * @return          解析后的二维码内容
     */
 
    public static String decode(String imgPath) {
 
        BufferedImage image = null;
 
        Result result = null;
 
        try {
 
            image = ImageIO.read(new File(imgPath));
 
            if (image == null) {
 
                return "the decode image may be not exit";
 
            }
 
            LuminanceSource source = new BufferedImageLuminanceSource(image);
 
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
 
            Map<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
 
            hints.put(DecodeHintType.CHARACTER_SET, "UTF8");
 
            result = new MultiFormatReader().decode(bitmap, hints);
 
            return result.getText();
 
        } catch (Exception e) {
 
            e.printStackTrace();
 
        }
 
        return null;
 
    }
 
    // 测试代码
    public static void main( String[] args ){
 
    	  QrCodeUtil.encode("http://www.521show.com/love/7/", 500, 500, "C:\\Users\\10517\\Desktop\\desktop\\qret.png");
//        System.out.println(QrCodeUtil.decode("D:\\David\\QrCode\\QrCode1.png"));
 
    }
 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值