zxing二维码的生成之路

zxing二维码的生成之路

因项目需求,前段时间使用BarCode4j框架,完成了条形码的生成和解析
最近又有新的需求,二维码的生成和解析!我好难,我只是小白。
没有师兄,没办法自己整就完了。(ps:自由独立探索,会让你学得更多)
百度常用框架:QrCode 和 ZXing

  1. QrCode.jar可以在https://mvnrepository.com/MVN库下载(我找了很久!),前端还可以采用qrcode.js插件。具体用法请自行百度。
    本人认为可帮助网站:https://github.com/davidshimjs/qrcodejs
    2.ZXing.jar
    只需配置pom.xml
    <!--二维码-->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.1.0</version>
        </dependency>

顺便记录maven阿里云配置指南
阿里云公共代理库

打开maven的配置文件(windows机器一般在maven安装目录的conf/settings.xml),在标签中添加mirror子节点:

<mirror>
    <id>aliyunmaven</id>
    <mirrorOf>*</mirrorOf>
    <name>阿里云公共仓库</name>
    <url>https://maven.aliyun.com/repository/public</url>
</mirror>

下面记录核心操作:创建ZXingUtils工具类,方便调用
二维码的创建

 /**
     *
     * @param imgPath
     * @param format
     * @param content 需要加密的文本
     *
     * @param width
     * @param height
     * @param logo
     * @throws Exception
     */
    public static void encodeImg(String imgPath,String format,String content,int width,int height,String logo) throws Exception {
        Hashtable<EncodeHintType,Object > hints = new Hashtable<EncodeHintType,Object>();
        //设置编码方式
        hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
        //设置二维码纠错级别
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        //设置二维码边的空度,非负数
        hints.put(EncodeHintType.MARGIN,1);

        /**
         * BarcodeFormat.QR_CODE  需要创建的类型(二维码)
         *
         */
        BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,width,height,hints);


        //绘制成图片
       /* BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);*/
        /**
         * setRGB中的三个参数都为int类型
         * 其中matrix.get(x,y)返回boolean类型,
         * 0代表黑
         * -1代表白
         * Color.WHITE返回结果是Color对象,不知道选择哪个包下的Color类才返回int
         */
      /*  for(int x=0;x
        //输出图片
        /*  ImageIO.write(image,format,new File(imgPath));*/

        /**
         * 这一行代码就可以替代上面代码
         */
        MatrixToImageWriter.writeToPath(matrix,format,new File(imgPath).toPath());
		 /**
         * 添加logo方法addLogo()
         */
        MatrixToImageConfig matrixToImageConfig = new MatrixToImageConfig(0xFF000001, 0xFFFFFFFF);
        BufferedImage bufferedImage = addLogo(MatrixToImageWriter.toBufferedImage(matrix,matrixToImageConfig), new File("D:\\logo.png"));
        ImageIO.write(bufferedImage,"png",new File("D:\\newZxing.png"));
    }

下面代码可用
MatrixToImageWriter.writeToPath(matrix,format,new File(imgPath).toPath());
一行代码代替。

  //绘制成图片
       BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);*/
        /**
         * setRGB中的三个参数都为int类型
         * 其中matrix.get(x,y)返回boolean类型,
         * 0代表黑
         * -1代表白
         * Color.WHITE返回结果是Color对象,不知道选择哪个包下的Color类才返回int
         */
        for(int x=0;x<width;x++){
            for (int y=0;y<height;y++){
                image.setRGB(x,y, (matrix.get(x,y)?0:-1) );
            }
        }
        //输出图片
         ImageIO.write(image,format,new File(imgPath));

下面生成logo代码借鉴于他人,原文链接

/**
     * 给二维码加Logo
     * @param matrixImage 原二维码
     * @param logoFile logo图片
     * @throws Exception
     */
    public static BufferedImage addLogo(BufferedImage matrixImage,File logoFile) throws Exception {
        /**
         * 读取二维码图片,并构建绘图对象
         */
        Graphics2D g2 = matrixImage.createGraphics();

        int matrixWidth = matrixImage.getWidth();
        int matrixHeigh = matrixImage.getHeight();

        /**
         * 读取Logo图片
         */
        BufferedImage logo = ImageIO.read(logoFile);

        //开始绘制图片
        g2.drawImage(logo,matrixWidth/5*2,matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5, null);//绘制
        BasicStroke stroke = new BasicStroke(5,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
        g2.setStroke(stroke);// 设置笔画对象
        //指定弧度的圆角矩形
        RoundRectangle2D.Float round = new RoundRectangle2D.Float(matrixWidth/5*2, matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5,20,20);
        g2.setColor(Color.white);
        g2.draw(round);// 绘制圆弧矩形

        //设置logo 有一道灰色边框
        BasicStroke stroke2 = new BasicStroke(1,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
        g2.setStroke(stroke2);// 设置笔画对象
        RoundRectangle2D.Float round2 = new RoundRectangle2D.Float(matrixWidth/5*2+2, matrixHeigh/5*2+2, matrixWidth/5-4, matrixHeigh/5-4,20,20);
        g2.setColor(new Color(128,128,128));
        g2.draw(round2);// 绘制圆弧矩形

        g2.dispose();
        matrixImage.flush() ;
        return matrixImage ;
    }

二维码解密如下:

 /**
     * 二维码解密
     * @param file
     * @return
     * @throws Exception
     */
    public static String decodeImg(File file) throws Exception {
        if(!file.exists()) return null;

        /**
         * 二维码解密核心
         */
        MultiFormatReader formatReader = new MultiFormatReader();
        //将图片读到内存
        BufferedImage image = ImageIO.read(file);
        /**
         * 核心代码 记住就好,理解需要阅读源码
         */
      /*  LuminanceSource source = new BufferedImageLuminanceSource(image);
        Binarizer binarizer = new HybridBinarizer(source);
        BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);*/
        BinaryBitmap binaryBitmap =new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));

        Map map = new HashMap();
        map.put(EncodeHintType.CHARACTER_SET,"utf-8");
        Result result = formatReader.decode(binaryBitmap,map);
        /**
         * result.getBarcodeFormat() 获取二维码格式类型
         */
        return result.toString();
    }

测试代码:

  public static void main(String[] args) throws Exception {
        String imgPath = "D:\\zxing.png";
        String format = "png";
        String content = "这是第一次生成二维码";

        encodeImg(imgPath,format,content,300,300,"");
        System.out.println("二维码生成成功");

       /* File file = new File("D:\\zxing.png");
        String result = decodeImg(file);
        System.out.println("二维码解码结果:"+result);*/
    }

结果图片(放心扫描)
zxing二维码的生成之路_第1张图片

总结:
有了条形码的实践之后,二维码理解和应用起来比较容易。本身操作并不是很困难,困难的是自己如何去寻找答案。这两次实践让我意识到自己java基础方面的不足,IO流的知识薄弱,遇到流方面的知识自己的思维就会混乱。原因在于自己对于io流的理解不够,会花时间去学习。包括BufferedImage类和ImageIO.read()和ImageIO.whrite()方法的学习。
自己也会将学习io流的历程记录起来,方便回忆和学习

如有侵权,联系删除。博客记录学习,传播知识

你可能感兴趣的:(java,二维码和条形码)