Java二维码生成和解析

来源:互联网 发布:淘宝旺铺专业版价格 编辑:程序博客网 时间:2024/05/29 02:42

二维码生成:

引用的包:        <dependency>            <groupId>com.google.zxing</groupId>            <artifactId>core</artifactId>            <version>2.2</version>        </dependency>        <dependency>            <groupId>com.google.zxing</groupId>            <artifactId>javase</artifactId>            <version>2.2</version>        </dependency>
生成代码:    /**     *     * @Title: createQrCodeByStringName    * @param @param path 生成二维码路径    * @param @param name  二维码名称    * @param @param content 二维码存储的信息    * @param @param qrCodeSize  二维码长度和宽度    * @param @param imageFormat 图片类型    * @param @throws WriterException    * @param @throws IOException    设定文件    * @return void    返回类型    * @throws     */    public static void createQrCodeByStringName(String path,String name, String content, int qrCodeSize, String imageFormat) throws WriterException, IOException{          FileOutputStream outputStream = new FileOutputStream(new File(path+name));        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();          hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");          BitMatrix bitMatrix = new MultiFormatWriter().encode(content,                  BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hints);// 生成矩阵          MatrixToImageWriter.writeToStream(bitMatrix, imageFormat, outputStream);// 输出图像          System.out.println("二维码生成成功.");       } 
二维码解析:    /**     * 读二维码并输出携带的信息     */    public static void readQrCode(FileInputStream inputStream) throws IOException{          BufferedImage image;          try {              image = ImageIO.read(inputStream);              LuminanceSource source = new BufferedImageLuminanceSource(image);              Binarizer binarizer = new HybridBinarizer(source);              BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);              Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();              hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");              Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码              System.out.println("二维码扫描结果:"+result.getText());        } catch (IOException e) {              e.printStackTrace();          } catch (NotFoundException e) {              e.printStackTrace();          }       }
测试代码:    /**     * 测试代码     * @throws WriterException      * @throws ParseException      */    public static void main(String[] args) throws IOException, WriterException, ParseException { createQrCodeByStringName("d:\\","www.jpg","哈哈哈哈",500,"JPEG"); readQrCode(new FileInputStream(new File("d:\\www.jpg")));      }  
原创粉丝点击