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();
            }
        }
    
    }
  • 相关阅读:
    【web安全】浅谈web安全之XSS
    【css】浅谈BFC
    nodejs笔记一--模块,全局process对象;
    逼真打字机效果;
    深入理解CSS3 animation的steps
    网址链接收藏
    用hoverclock插件实现HTML5时钟
    JS多种方法实现随机颜色;
    canvas实现跟随鼠标旋转的箭头
    封装insertAfter、addClass、格式化时间
  • 原文地址:https://www.cnblogs.com/zgsyjn/p/6035229.html
Copyright © 2011-2022 走看看