Zxing实现二维码生成和解析,可带logo

来源:互联网 发布:网络维保服务模式 编辑:程序博客网 时间:2024/05/17 09:32

在项目中使用zxing生成二维码提供项目支撑(ZXing是一个开源Java类库用于解析多种格式的条形码和二维码),其余SwetakeQRCode、BarCode4j等等工具可去了解。


简单介绍:

二维条形码最早发明于日本,它是用某种特定的几何图形按一定规律在平面(二维方向上)分布的黑白相间的图形记录数据符号信息的,在代码编制上巧妙地利用构成计算机内部逻辑基础的“0”、“1”比特流的概念,使用若干个与二进制相对应的几何形体来表示文字数值信息,通过图象输入设备或光电扫描设备自动识读以实现信息自动处理。它具有条码技术的一些共性:每种码制有其特定的字符集;每个字符占有一定的宽度;具有一定的校验功能等。同时还具有对不同行的信息自动识别功能、及处理图形旋转变化等特点。


ps:(可能是Zxing网络上解决方案比较多,再说下,QRCode是日本人开发的,ZXing是google开发,barcode4j也是老美开发的,barcode4j对一维条形码处理的很好,而且支持的格式很多,当然也可以对二维码进行处理,效果个人感觉没有前两种好;ZXing对j2me,j2se,还有Android等支持也比较好,如果你是搞Android的或以后准备走Android,建议还是用zxing的比较好

第一步:将二维码矩阵输出到图片上面

01<strong>package t1;
02 
03import java.awt.image.BufferedImage;
04import java.io.File;
05import java.io.IOException;
06import java.io.OutputStream;
07 
08import javax.imageio.ImageIO;
09 
10import com.google.zxing.common.BitMatrix;
11 
12 
13   
14/**
15 * 二维码的生成需要借助MatrixToImageWriter类,该类是由Google提供的,可以将该类直接拷贝到源码中使用,当然你也可以自己写个
16 * 生产条形码的基类
17 */ 
18public class MatrixToImageWriter {  
19    private static final int BLACK = 0xFF000000;//用于设置图案的颜色  
20    private static final int WHITE = 0xFFFFFFFF//用于背景色  
21   
22    private MatrixToImageWriter() {  
23    
24   
25    public static BufferedImage toBufferedImage(BitMatrix matrix) {  
26        int width = matrix.getWidth();  
27        int height = matrix.getHeight();  
28        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
29        for (int x = 0; x < width; x++) {  
30            for (int y = 0; y < height; y++) {  
31                image.setRGB(x, y,  (matrix.get(x, y) ? BLACK : WHITE)); 
32//              image.setRGB(x, y,  (matrix.get(x, y) ? Color.YELLOW.getRGB() : Color.CYAN.getRGB())); 
33            
34        
35        return image;  
36    
37   
38    public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {  
39        BufferedImage image = toBufferedImage(matrix); 
40        //设置logo图标 
41        LogoConfig logoConfig = new LogoConfig();  
42        image = logoConfig.LogoMatrix(image); 
43           
44        if (!ImageIO.write(image, format, file)) {  
45            throw new IOException("Could not write an image of format " + format + " to " + file);  
46        }else
47            System.out.println("图片生成成功!"); 
48        
49    
50   
51    public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throwsIOException { 
52        BufferedImage image = toBufferedImage(matrix); 
53        //设置logo图标 
54        LogoConfig logoConfig = new LogoConfig();  
55        image = logoConfig.LogoMatrix(image); 
56           
57        if (!ImageIO.write(image, format, stream)) {  
58            throw new IOException("Could not write an image of format " + format);  
59        
60    
61}</strong>

第二步:主要处理logo图标已达到和微信自动的二维码相近的效果

01<strong>package t1;
02 
03import java.awt.BasicStroke;  
04import java.awt.Color;  
05import java.awt.Graphics2D;  
06import java.awt.geom.RoundRectangle2D;  
07import java.awt.image.BufferedImage;  
08import java.io.File;  
09import java.io.IOException;  
10import javax.imageio.ImageIO;  
11/**
12 * 二维码 添加 logo图标 处理的方法,
13 * 模仿微信自动生成二维码效果,有圆角边框,logo和二维码间有空白区,logo带有灰色边框
14 * @author Administrator sangwenhao
15 *
16 */ 
17public class LogoConfig {  
18       
19    /**
20     * 设置 logo 
21     * @param matrixImage 源二维码图片
22     * @return 返回带有logo的二维码图片
23     * @throws IOException
24     * @author Administrator sangwenhao
25     */ 
26     public BufferedImage LogoMatrix(BufferedImage matrixImage) throws IOException{  
27         /**
28          * 读取二维码图片,并构建绘图对象
29          */ 
30         Graphics2D g2 = matrixImage.createGraphics(); 
31            
32         int matrixWidth = matrixImage.getWidth();  
33         int matrixHeigh = matrixImage.getHeight();  
34            
35         /**
36          * 读取Logo图片
37          */ 
38         BufferedImage logo = ImageIO.read(new File("E:\\heack.jpg"));  
39   
40         //开始绘制图片 
41         g2.drawImage(logo,matrixWidth/5*2,matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5null);//绘制      
42         BasicStroke stroke = new BasicStroke(5,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);   
43         g2.setStroke(stroke);// 设置笔画对象 
44         //指定弧度的圆角矩形 
45         RoundRectangle2D.Float round = newRoundRectangle2D.Float(matrixWidth/5*2, matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5,20,20); 
46         g2.setColor(Color.white); 
47         g2.draw(round);// 绘制圆弧矩形 
48            
49         //设置logo 有一道灰色边框 
50         BasicStroke stroke2 = new BasicStroke(1,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);   
51         g2.setStroke(stroke2);// 设置笔画对象 
52         RoundRectangle2D.Float round2 = newRoundRectangle2D.Float(matrixWidth/5*2+2, matrixHeigh/5*2+2, matrixWidth/5-4, matrixHeigh/5-4,20,20); 
53         g2.setColor(new Color(128,128,128));  
54         g2.draw(round2);// 绘制圆弧矩形 
55            
56         g2.dispose(); 
57         matrixImage.flush() ; 
58         return matrixImage ;  
59     
60       
61}</strong>
第三步:主方法操作类


01<strong>package t1;
02 
03import java.io.File;
04import java.io.IOException;
05import java.util.Hashtable;
06 
07import com.google.zxing.BarcodeFormat;
08import com.google.zxing.EncodeHintType;
09import com.google.zxing.MultiFormatWriter;
10import com.google.zxing.WriterException;
11import com.google.zxing.common.BitMatrix;
12import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
13   
14public class EncodeTest {  
15       
16    public static void Encode_QR_CODE() throws IOException, WriterException{  
17        String contents = "ZXing 二维码内容1234!"// 二维码内容 
18        int width = 430// 二维码图片宽度 300   
19        int height = 430// 二维码图片高度300  
20           
21        String format = "gif";// 二维码的图片格式 gif 
22           
23        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();  
24         // 指定纠错等级,纠错级别(L 7%、M 15%、Q 25%、H 30%) 
25        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); 
26        // 内容所使用字符集编码 
27        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");    
28//      hints.put(EncodeHintType.MAX_SIZE, 350);//设置图片的最大值 
29//      hints.put(EncodeHintType.MIN_SIZE, 100);//设置图片的最小值 
30        hints.put(EncodeHintType.MARGIN, 1);//设置二维码边的空度,非负数 
31           
32        BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,//要编码的内容  
33                //编码类型,目前zxing支持:Aztec 2D,CODABAR 1D format,Code 39 1D,Code 93 1D ,Code 128 1D, 
34                //Data Matrix 2D , EAN-8 1D,EAN-13 1D,ITF (Interleaved Two of Five) 1D, 
35                //MaxiCode 2D barcode,PDF417,QR Code 2D,RSS 14,RSS EXPANDED,UPC-A 1D,UPC-E 1D,UPC/EAN extension,UPC_EAN_EXTENSION 
36                BarcodeFormat.QR_CODE, 
37                width, //条形码的宽度 
38                height, //条形码的高度 
39                hints);//生成条形码时的一些配置,此项可选 
40           
41        // 生成二维码 
42        File outputFile = new File("e:" + File.separator + "new-1.gif");//指定输出路径  
43           
44        MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile); 
45    
46       
47    public static void main(String[] args) throws Exception {  
48        try {  
49            Encode_QR_CODE(); 
50        catch (Exception e) {  
51            // TODO: handle exception 
52            e.printStackTrace(); 
53        
54    
55       
56}</strong>

注意事项:二维码生成可根据自己需要的文件流生成二维码,同时,上传logo需要源文件读取。关于使用Zxing生成二维码解码报NotFoundException异常问题,遇到Zxing生成的二维码进行解码的时候报出NotFoundException异常问题,在使用Maven对源码进行编译的时候提示编译unsupported major.minorversion 51.这个与我的编译环境有关系,当时默认的JDK1.6.x,当我重新下载了最新版本的JDKjdk1.7.0_45并设置为编译环境,这个时候对源代码编译成功,并且再次运行3中的代码仍然是unsupported major.minor version51这个问题,这个时候就是开发工具锅了,Eclipse中要设置对于的JRE和编译版本。这样这个问题就解决了。

阅读全文
1 0
原创粉丝点击