使用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();
        }

    }

}

解析的内容如下:

时间: 2024-08-07 08:39:29

使用zxing生成和解析二维码的相关文章

Java使用Zxing生成、解析二维码工具类

Zxing是Google提供的关于条码(一维码.二维码)的解析工具,提供了二维码的生成与解析的方法. 1.二维码的生成 (1).将Zxing-core.jar 包加入到classpath下. (2).二维码的生成需要借助MatrixToImageWriter类,该类是由Google提供的; package com.qlwb.business.util; //导入省略... /** * 二维码工具类 * */ public class MatrixToLogoImageWriter { priva

用zxing生成和解析二维码

package test; 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 org.junit.Test; import com.google.zxing.BarcodeFormat; import com

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

pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4

zxing生成和解析二维码

今天忙了一天的二维码,用了QRcode和ZXing两个开源包.结果发现 ZXing比QRcode更好用一些,它直接可以定义二维码生成图案的大小,而QRcode生成的二维码是根据二维码包含的内容多少来定的.所以生成的二维码图片大小不好确定. 下面主要说一下ZXing生成二维码的方法: ZXing是google的开源资源,但是由于中国的某些原因使得访问谷歌的资源比较难,所以在网上找到了一个可以下载的连接:http://www.cr173.com/soft/65529.html 下载好需要的核心jar

java生成和解析二维码

前言 现在,二维码的应用已经非常广泛,在线生成器也是诸多,随手生成. 所以就和大家分享一个小案例,用zxing来做一个的二维码生成器,当然这个例子是比较简单,若是写的不好请多多包涵. ZXING项目是谷歌推出的用来识别多种格式条形码的开源项目,项目地址为https://github.com/zxing/zxing. 1.加载zxing依赖 用idea新建个maven项目,pom.xml添加对应的依赖 <dependency> <groupId>com.google.zxing<

Java使用QRCode.jar生成与解析二维码

正题:Java使用QRCode.jar生成与解析二维码demo 欢迎新手共勉,大神监督指正 # 不知道QRCode的请移步wiki,自行了解,这里不多做解释 *******创建二维码之前的工作******** 去下面给出的地址下载QRCode.jar包,此jar包已经包括 生成与解析 . 官网下载到的jar包是没有解析的 https://files.cnblogs.com/files/bigroc/QRCode.zip ***创建好你的测试类导好jar包开始吧*** 第一部分:生成二维码 pac

java利用zxing生成仿新浪微博二维码

原文:java利用zxing生成仿新浪微博二维码 源代码下载地址:http://www.zuidaima.com/share/1550463729896448.htm 效果图: 说明在readme.txt文件

C# 生成和解析二维码

下面是C#和JAVA两个版本的开放源码下载: C#:http://www.codeproject.com/Articles/20574/Open-Source-QRCode-Library JAVA:https://github.com/zxing/zxing 本人只测试过了C#版本的,下面是测试过程中遇到的问题以及解决办法: 1.第一次运行报错信息如下: 错误     “ThoughtWorks.QRCode.Properties.Resources”并不包含“GetResource”的定义

.Net mvc 使用QRCode生成和解析二维码

//index 控制器中的代码 using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Web; using System.Web.Mvc; using ThoughtWorks.QRCode.Codec; namespace MyQrCode.Controllers { public class IndexController : Controll