二维码功能实现简单例子

//所需jar包下载地址:http://download.csdn.net/download/huchgu/9996818

//二维码演示实现类,支持中文无乱码,在项目中导入所需jar即可运行

public class QrcodeDemo {  
  
    public static void main(String[] args) {
        String str = "https://github.com/zxing/zxing";  //二维码内容
        String path = "E:/test.png";                               //二维码图片生成路径
        QrcodeDemo t = new QrcodeDemo();          //实例化演示类
        t.encode(str, path,400,400);                            //生成二维码图片

        

        String res = t.decode(path);                            //根据传入的2维码图片所在路径,解析得到二维码图片里的内容

        System.out.println("解码结果:"+res);          //打印扫描结果
    }  
  
    /* 编码:生成二维码图片
     * str:二维码内容  
     * path:二维码图片生成 路径及名称,如 D:/Qr_pics/test.png
     * width:设置二维码图片宽的长度
     * height:设置二维码图片高的长度
     * */

    public void encode(String str, String path,int width,int height) {  
        try {  
            BitMatrix byteMatrix = new MultiFormatWriter()
            .encode(str, BarcodeFormat.QR_CODE, width, height);  //后两个参数设置二维码图片大小-图片像素大小 
            File file = new File(path);                                                         //新建矩阵文件  
            MatrixToImageWriter.writeToFile(byteMatrix, "gif", file);     //将矩阵文件转换成图片文件  
        } catch (Exception e) {  
            e.printStackTrace();
        }  
    }  
  
    /*
     * 解码:获取二维码里的内容
     * imgPath:即将被解码图片的路径,如 D:/Qr_pics/test.png
     * */ 

    public String decode(String imgPath) {  
         try {  
              File file = new File(imgPath);                           //获取该图片文件  
              BufferedImage image = ImageIO.read(file);
              if (image != null) {
        LuminanceSource source = new BufferedImageLuminanceSource(image);  
                   BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));  
                   Hashtable hashtable = new Hashtable();                                      //将图片反解码为二维矩阵  
                   hashtable.put(DecodeHintType.CHARACTER_SET, "UTF-8");  
                   Result result = new MultiFormatReader().decode(bitmap, hashtable);  //将该二维矩阵解码成内容  
                   return result.getText();
              }
         } catch (Exception e) {  
    e.printStackTrace();
         }
         return null;
    }  
      
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值