美文网首页Android_plusplus工具癖@IT·互联网
java——基于zxing的二维码生成器

java——基于zxing的二维码生成器

作者: 李庆文 | 来源:发表于2016-09-05 19:57 被阅读10052次

随着扫一扫的流行,二维码也开始变得非常的火热,本篇文章就用最近比较流行的zxing来做一个属于自己的二维码生成器。当然这个这个比较简单,抛砖引玉。如果大家还希望看二维码细节,请参考陈皓大神的这篇文章
二维码的生成细节和原理

java二维码生成

一.资源需求

  • 1下载zxing工程
    github地址zxing项目 github
  • 2下载之后将code生成jar包然后导入到我们自己的工程中去。(这一步不是很清楚,等待之后弄明白)
    这里提供一下已经生成好的jar包。[zxing jar包百度云分享](链接:http://pan.baidu.com/s/1kVvwgj9 密码:pa5g) 如果分享被取消可以在文章下面评论或者是通过简信联系我。
  • 3通过通过google测试的matrixToImageWriter进行辅助开发。
  • 4进行各种编辑。

二 代码开发。

判断代码的好坏之一就是耦合性低,所以我对代码进行了一定的封装,如果大家仅仅是为了不求甚解的话,可以直接使用下面的代码。

  • 1 引入jar包。自行百度。
  • 2 代码编写
    • matrixToImageWriter类
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import com.google.zxing.common.BitMatrix;

/*
  二维码的生成需要借助MatrixToImageWriter类,该类是由Google提供的,可以将该类直接拷贝到源码中使用,当然你也可以自己写个
  生产条形码的基类
 */
public class MatrixToImageWriter {
    private static final int BLACK = 0xFF000000;//用于设置图案的颜色
    private static final int WHITE = 0xFFFFFFFF; //用于背景色

    private MatrixToImageWriter() {
    }

    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y,  (matrix.get(x, y) ? BLACK : WHITE));
//              image.setRGB(x, y,  (matrix.get(x, y) ? Color.YELLOW.getRGB() : Color.CYAN.getRGB()));
            }
        }
        return image;
    }

    public static void writeToFile(BitMatrix matrix, String format, File file,String logUri) throws IOException {
        
        System.out.println("write to file");
        BufferedImage image = toBufferedImage(matrix);
        //设置logo图标
        QRCodeFactory logoConfig = new QRCodeFactory();
        image = logoConfig.setMatrixLogo(image, logUri);
        
        if (!ImageIO.write(image, format, file)) {
            System.out.println("生成图片失败");
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }else{
            System.out.println("图片生成成功!");
        }
    }

    public static void writeToStream(BitMatrix matrix, String format, OutputStream stream,String logUri) throws IOException {
        
        BufferedImage image = toBufferedImage(matrix);
        
        //设置logo图标
        QRCodeFactory logoConfig = new QRCodeFactory();
        image = logoConfig.setMatrixLogo(image, logUri);
        
        if (!ImageIO.write(image, format, stream)) {
            throw new IOException("Could not write an image of format " + format);
        }
    }
}

  • 接下来是QRCodeFactory
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
 * 本类用于对我们二维码进行参数的设定,生成我们的二维码:
 * @author kingwen
 */
public class QRCodeFactory {
    
    /**
     * 给生成的二维码添加中间的logo
     * @param matrixImage 生成的二维码
     * @param logUri      logo地址
     * @return            带有logo的二维码
     * @throws IOException logo地址找不到会有io异常
     */
     public BufferedImage setMatrixLogo(BufferedImage matrixImage,String logUri) throws IOException{
         /**
          * 读取二维码图片,并构建绘图对象
          */
         Graphics2D g2 = matrixImage.createGraphics(); 
         int matrixWidth = matrixImage.getWidth();
         int matrixHeigh = matrixImage.getHeight();
         
         /**
          * 读取Logo图片
          */
         BufferedImage logo = ImageIO.read(new File(logUri));

         //开始绘制图片
         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 content            二维码内容
      * @param format             生成二维码的格式
      * @param outFileUri         二维码的生成地址
      * @param logUri             二维码中间logo的地址
      * @param size               用于设定图片大小(可变参数,宽,高)
      * @throws IOException       抛出io异常
      * @throws WriterException   抛出书写异常
      */
     public  void CreatQrImage(String content,String format,String outFileUri,String logUri, int ...size) throws IOException, WriterException{
   
         
        int width = 430; // 二维码图片宽度 430 
        int height = 430; // 二维码图片高度430 
        
        //如果存储大小的不为空,那么对我们图片的大小进行设定
        if(size.length==2){
        width=size[0];
        height=size[1];
        }else if(size.length==1){
           width=height=size[0];
        }
        
        
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
         // 指定纠错等级,纠错级别(L 7%、M 15%、Q 25%、H 30%)
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 内容所使用字符集编码
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");   
        //hints.put(EncodeHintType.MAX_SIZE, 350);//设置图片的最大值
        //hints.put(EncodeHintType.MIN_SIZE, 100);//设置图片的最小值
        hints.put(EncodeHintType.MARGIN, 1);//设置二维码边的空度,非负数
        
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,//要编码的内容
                //编码类型,目前zxing支持:Aztec 2D,CODABAR 1D format,Code 39 1D,Code 93 1D ,Code 128 1D,
                //Data Matrix 2D , EAN-8 1D,EAN-13 1D,ITF (Interleaved Two of Five) 1D,
                //MaxiCode 2D barcode,PDF417,QR Code 2D,RSS 14,RSS EXPANDED,UPC-A 1D,UPC-E 1D,UPC/EAN extension,UPC_EAN_EXTENSION
                BarcodeFormat.QR_CODE,
                width, //条形码的宽度
                height, //条形码的高度
                hints);//生成条形码时的一些配置,此项可选
            
        // 生成二维码图片文件
        File outputFile = new File(outFileUri);
        
        //指定输出路径    
        System.out.println("输出文件路径为"+outputFile.getPath());
        
        MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile,logUri);
    }   
}

最后是我们的测试类

import java.io.File;
import java.io.IOException;

import com.google.zxing.WriterException;

public class Qrest {

    public static void main(String[] args) {

        String content="大家好,我是李庆文,很高兴认识大家";
     String logUri="***";
     String outFileUri="***";
     int[]  size=new int[]{430,430};
     String format = "jpg";  
     
       try {
        new QRCodeFactory().CreatQrImage(content, format, outFileUri, logUri,size);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (WriterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   
  }

}

然后我们就可以自由的去定制属于我们自己的二维码了。

大家好,我是李庆文

希望大家玩的开心啊~

【注】本文章为sanfye博客ZXing生成二维码和带logo的二维码,模仿微信生成二维码效果的学习笔记。

相关文章

网友评论

  • khl小城:怎么生成你的那个二维码 替换logUri和outFileUri成网址就OK嘛?
  • AYSAML:楼主,请问用这个程序可以生成那种用微信扫描就访问一个网址的二维码吗?
    AYSAML:@李庆文 好的,谢谢
    李庆文:@为谁抚琴 可以,只要把那个内容换成你的网址的url即可。非常方便。
  • f978f52c3fa4:BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width,height, hints);
    为什么这里总是提示我类型不符,总让我将BitMatrix转换成ByteMatrix;
    还有, hints.put(EncodeHintType.MARGIN, 1);
    这行代码提示我EncodeHintType无法调到MARGIN 是怎么回事,请指教
    f978f52c3fa4:刚刚下载了楼主的jar包用,问题解决了,哈哈哈
  • clearCode:能不能在生成的二维码下面显示一行字呢
    3a97de4358d5:@clearCode 你好 怎么解决的呢
    clearCode:@李庆文 已经解决啦,谢谢
    李庆文:你自己试一下吧,应该是可以的。看一下具体是在哪一部分进行了图片的制作,主要应该是在画布生成的地方进行修改 。我现在在准备考研,所以我也暂时不能帮忙啦。你自己加油啦~
  • e23b92a9a4ed:zxing jar包百度云分享 链接打不开,能提供下吗?
    李庆文:@豆芽小哥 链接:http://pan.baidu.com/s/1bYoQNs 密码:24r1 试一下~
  • 630905c56c2c:多谢分享
    李庆文:一起加油啦~
  • 630905c56c2c:可以不添加LOGO吗?
    f978f52c3fa4:@3kqing 怎么解决 的
    630905c56c2c:已解决
  • 不是南风:不错
    李庆文:@不是南风 :smile:
  • 0672f401d3a4:思路清晰,代码明了。拜读了
    李庆文:@天真无邪小郎君 谢谢谢谢~被认可的感觉真的好棒~

本文标题:java——基于zxing的二维码生成器

本文链接:https://www.haomeiwen.com/subject/lxnrettx.html