使用zxing生成和解析二维码

Posted 愤怒的绿萝

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用zxing生成和解析二维码相关的知识,希望对你有一定的参考价值。

二维码:
  是用某种特定的几何图形按一定规律在平面(二维方向上)分布的黑白相间的图形记录数据符号信息的;
  在代码编制上巧妙的利用构成计算机内部逻辑基础的0和1比特流的概念,使用若干个与二进制相对应的几何形体来表示文字数值信息,通过图像输入设备或光电扫描设备自动识读以实现信息自动处理;
  二维码能够在横向和纵向两个方位同时表达信息,因此能在很小的面积内表达大量的信息;
  二维码相对于条形码的优势就是省空间;

zxing简介:
  zxing是一个开放源码的,用Java实现的多种格式的1D/2D条码图像处理库,它包含了联系到其他语言的接口。
  zxing可以实现使用手机的内置的摄像头完成条形码和二维码的扫描与解码。
  zxing可以实现条形码和二维码的编码与解码。
  zxing目前支持的的格式如下:
  UPC-A,UPC-E
  EAN-8,EAN-13
  39码
  93码
  代码128
  QR码

项目环境:
  jdk1.6 myEclipse10 zxing-core-2.2.jar(如果版本太高,出现版本不支持错误)

项目目录树

  

一:二维码生成
  二维码生成需要借助MatrixToImageWriter类,该类是由Google提供

 package com.dlab.xzing;

 
 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;
 
 
 public final 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);
           }
       }
       
     return image;
     
   }
 
   
   public static void writeToFile(BitMatrix matrix, String format, File file)
       throws IOException {
       
               BufferedImage image = toBufferedImage(matrix);
               
               if (!ImageIO.write(image, format, file)) {
                   throw new IOException("Could not write an image of format " + format + " to " + file);
               }
   }
 
   
   public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)
       throws IOException {
       
               BufferedImage image = toBufferedImage(matrix);
               
               if (!ImageIO.write(image, format, stream)) {
                   throw new IOException("Could not write an image of format " + format);
               }
   }
 
 }

使用CreateImage类生成二维码:

package com.dlab.xzing;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;



public class CreateImage {

    public static void main(String[] args) {

        try {
            String content = "http://www.baidu.com";
            
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            
            Map hints = new HashMap();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            
            BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400, 400, hints);
            
            File file = new File("cjz.jpg");
            MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file);
            
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }

}

生成的二维码如下:

 

 

二:解析二维码
  二维码解析需要借助BufferedImageLuminanceSource类,该类是由Google提供

 

package com.dlab.xzing;

 import com.google.zxing.LuminanceSource;
 
 import java.awt.Graphics2D;
 import java.awt.geom.AffineTransform;
 import java.awt.image.BufferedImage;
 
 public final class BufferedImageLuminanceSource extends LuminanceSource {
 
   private final BufferedImage image;
   private final int left;
   private final int top;
 
   public BufferedImageLuminanceSource(BufferedImage image) {
     this(image, 0, 0, image.getWidth(), image.getHeight());
   }
 
   public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {
     super(width, height);
 
     int sourceWidth = image.getWidth();
     int sourceHeight = image.getHeight();
     if (left + width > sourceWidth || top + height > sourceHeight) {
       throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
     }
 
     for (int y = top; y < top + height; y++) {
       for (int x = left; x < left + width; x++) {
         if ((image.getRGB(x, y) & 0xFF000000) == 0) {
           image.setRGB(x, y, 0xFFFFFFFF); // = white
         }
       }
     }
 
     this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);
     this.image.getGraphics().drawImage(image, 0, 0, null);
     this.left = left;
     this.top = top;
   }
 
   @Override
   public byte[] getRow(int y, byte[] row) {
     if (y < 0 || y >= getHeight()) {
       throw new IllegalArgumentException("Requested row is outside the image: " + y);
     }
     int width = getWidth();
     if (row == null || row.length < width) {
       row = new byte[width];
     }
     image.getRaster().getDataElements(left, top + y, width, 1, row);
     return row;
   }
 
   @Override
   public byte[] getMatrix() {
     int width = getWidth();
     int height = getHeight();
     int area = width * height;
     byte[] matrix = new byte[area];
     image.getRaster().getDataElements(left, top, width, height, matrix);
     return matrix;
   }
 
   @Override
   public boolean isCropSupported() {
     return true;
   }
 
   @Override
   public LuminanceSource crop(int left, int top, int width, int height) {
     return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);
   }
 
   @Override
   public boolean isRotateSupported() {
     return true;
   }
 
   @Override
   public LuminanceSource rotateCounterClockwise() {
 
       int sourceWidth = image.getWidth();
     int sourceHeight = image.getHeight();
 
     AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);
 
     BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);
 
     Graphics2D g = rotatedImage.createGraphics();
     g.drawImage(image, transform, null);
     g.dispose();
 
     int width = getWidth();
     return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);
   }
 
 }

使用ResolveImage类解析二维码:

package com.dlab.xzing;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;

public class ResolveImage {

    public static void main(String[] args) {


        
        try {
            MultiFormatReader multiFormatReader = new MultiFormatReader();
            
            File file = new File("cjz.jpg");
            
            BufferedImage image = ImageIO.read(file);
            
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            
            Binarizer binarizer = new HybridBinarizer(source);
            
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            
            Map hints = new HashMap();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            
            Result result = multiFormatReader.decode(binaryBitmap, hints);
            
            System.out.println("result: " + result.toString());
            System.out.println("resultFormat: " + result.getBarcodeFormat());
            System.out.println("resultText: " + result.getText());
            
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        
        
    }

}

解析的内容如下:

 

以上是关于使用zxing生成和解析二维码的主要内容,如果未能解决你的问题,请参考以下文章

使用zxing生成和解析二维码

java zxing实现二维码生成和解析zxing实现二维码生成和解析

Java通过Zxing生成和解析二维码

Java通过Zxing生成和解析二维码

使用Google ZXing生成和解析二维码

Java使用ZXing生成/解析二维码图片