zoukankan      html  css  js  c++  java
  • 利用JAVA生成二维码

    本文章整理于慕课网的学习视频《JAVA生成二维码》,如果想看视频内容请移步慕课网

    维基百科上对于二维码的解释.

    二维条码是指在一维条码的基础上扩展出另一具有可读性的条码,使用黑白矩形图案表示二进制数据,被设备扫描后可获取其中所包含的信息。一维条码的宽度记载着数据,而其长度没有记载数据。二维条码的长度、宽度均记载着数据。二维条码有一维条码没有的“定位点”和“容错机制”。容错机制在即使没有辨识到全部的条码、或是说条码有污损时,也可以正确地还原条码上的信息。

     


    利用JAVA生成QR Code格式的二维码

       相关jar包下载地址(ZXing.jar)。

    public class CreateQRCode {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            //设定二维码宽高,类型,二维码要展示的内容。
            int width = 300;
            int height = 300;
            String format = "png";
            String content = "https://www.baidu.com/";
            //定义二维码参数(格式,错误等级)
            HashMap hints = new HashMap();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.M);
            hints.put(EncodeHintType.MARGIN,2);
            
            try {    
                BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height);
                // 二维码生成路径
                Path file = new File("D:/code/img.png").toPath();
                MatrixToImageWriter.writeToPath(bitMatrix, format, file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    利用JAVA解析二维码

    public class ReadQRCode {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            MultiFormatReader formatReader = new MultiFormatReader();
            // 二维码路径
            File file = new File("D:/code/img.png");
            BufferedImage image;
            try {
                image = ImageIO.read(file);
                BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(
                        new BufferedImageLuminanceSource(image)));
                // 定义二维码参数(格式,错误等级)
                HashMap hints = new HashMap();
                hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
                Result result = formatReader.decode(binaryBitmap, hints);
                // 输出二维码内容
                System.out.println("解析结果:" + result.toString());
                System.out.println("解析结果:" + result.getBarcodeFormat());
                System.out.println("解析结果:" + result.getText());
            } catch (IOException | NotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    }
  • 相关阅读:
    ubuntu linux切换用户到root
    passwd命令
    如何根据驱动程序及其安装文件来访问该设备[转]
    CMMI的5个级别和25个过程域
    Linux操作系统启动过程
    VMWare上网三种工作模式
    卷积的意义【转】
    Linux内核模块动态添加方法
    Linux内核编译的过程
    mysql存入中文乱码解决方法(windows环境)
  • 原文地址:https://www.cnblogs.com/zgsyjn/p/6035229.html
Copyright © 2011-2022 走看看