博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java条形码和二维码解析
阅读量:212 次
发布时间:2019-02-28

本文共 9869 字,大约阅读时间需要 32 分钟。

java条形码和二维码解析

条形码(一维码)

  • 条形码(barcode)
    – 将宽度不等的多个黑条和空白,按照一定的编码规则排列,用以表达一组信息的图形标识符
    通常代表一串数字/字母,每一位有特殊含义
    一般数据容量30个数字/字母
    – 专门机构管理:中国物品编码中心

二维码

  • 二维码,二维条形码
    – 用某种特定的几何图形按一定规律在平面(二维方向上)分布的黑白相间的图形记录数据符号信息
    – 比一维条形码能存更多信息,表示更多数据类型
    – 能够存储数字/字母/汉字/图片等信息
    – 字符集128个字符
    – 可存储几百到几十KB字符
    – 抗损坏

二维码解析

java是没有解析二维码的库,我们只能依赖第三方jar包

Zxing(Zebra Crossin)

  • Zxing(Zebra Crossing)
    – Google出品
    – 支持1D和2D的Barcode
    – 主要类
    • BitMatrix位图矩阵
    • MultiFormatWriter位图编写器
    • MatrixToImageWriter写入图片
1D product 1D industrial 2D
UPC-A Code 39 QR Code
UPC - E Code 93 Data Matrix
EAN-8 Code 128 Aztec(beta)
EAN-13 Codabar PDF 417

Zxing 代码示例

pom.xml引入

com.google.zxing
core
3.3.3
com.google.zxing
javase
3.3.3
一维码生成及解析代码示例
package com.torey.javaAdvanced.mooc4.zxing;import com.google.zxing.*;import com.google.zxing.client.j2se.BufferedImageLuminanceSource;import com.google.zxing.client.j2se.MatrixToImageWriter;import com.google.zxing.common.BitMatrix;import com.google.zxing.common.HybridBinarizer;import javax.imageio.ImageIO;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.HashMap;import java.util.Map;/** * @ClassName:BarCodeTest * @Description: * @author: Torey */public class BarCodeTest {
/** * 根据code生成相应的一维码 * @param file 一维码目标文件 * @param code 一维码内容 * @param width 图片宽度 * @param height 图片高度 */ public static void generateCode(File file, String code,int width,int height){
//定义位图矩阵BitMatrix BitMatrix matrix=null; try{
//使用code_128格式进行表面生成100*25的条形码 MultiFormatWriter writer = new MultiFormatWriter(); matrix= writer.encode(code,BarcodeFormat.CODE_128,width,height,null); // matrix= writer.encode(code,BarcodeFormat.EAN_13,width,height,null); }catch (Exception ex){
ex.printStackTrace();} //将位图矩阵BitMatrix保存为图片 try(FileOutputStream outStream =new FileOutputStream(file)){
ImageIO.write(MatrixToImageWriter.toBufferedImage(matrix),"png",outStream); outStream.flush(); } catch (FileNotFoundException e) {
e.printStackTrace(); } catch (IOException e) {
e.printStackTrace(); } } public static void main(String[] args){
generateCode(new File("1dcode.png"),"123456789012",500,250); readCode(new File("1dcode.png")); } /** * 解析一维码 * @param file */ private static void readCode(File file) {
try{
BufferedImage read = ImageIO.read(file); if (null==read) {
return; } BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(read); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Map
hints=new HashMap<>(); hints.put(DecodeHintType.CHARACTER_SET,"GBK"); hints.put(DecodeHintType.PURE_BARCODE,Boolean.TRUE); hints.put(DecodeHintType.TRY_HARDER,Boolean.TRUE); Result decode = new MultiFormatReader().decode(bitmap, hints); System.out.println("条形码的内容是:"+decode.getText()); }catch (Exception ex){
} }}
二维码生成及解析示例代码
package com.torey.javaAdvanced.mooc4.zxing;import com.google.zxing.*;import com.google.zxing.client.j2se.BufferedImageLuminanceSource;import com.google.zxing.client.j2se.MatrixToImageWriter;import com.google.zxing.common.BitMatrix;import com.google.zxing.common.HybridBinarizer;import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;import javax.imageio.ImageIO;import java.awt.image.BufferedImage;import java.io.File;import java.nio.file.Path;import java.util.HashMap;import java.util.Map;/** * @ClassName:QRCodeTest * @Description:二维码 * @author: Torey */public class QRCodeTest {
/* 定义二维码的宽高 */ private static int WIDTH=300; private static int HEIGHT=300; private static String FORMAT="png";//二维码格式 //生成二维码 public static void generateQRCode(File file, String content){
//定义二维码参数 Map
hints=new HashMap<>(); //设置编码 hints.put(EncodeHintType.CHARACTER_SET,"utf-8"); //设置容错等级 hints.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.M); //设置边距默认是5 hints.put(EncodeHintType.MARGIN,2); try{
//把内容写进二维码中 BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints); Path path = file.toPath(); //写入指定路径下 MatrixToImageWriter.writeToPath(bitMatrix,FORMAT,path); }catch (Exception ex){
ex.printStackTrace(); } } public static void main(String[] args){
generateQRCode(new File("2dcode.png"),"http://www.baidu.com"); readQrCode(new File("2dcode.png")); } private static void readQrCode(File file) {
MultiFormatReader reader = new MultiFormatReader(); try{
BufferedImage image = ImageIO.read(file); BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image))); Map
hints=new HashMap(); hints.put(DecodeHintType.CHARACTER_SET,"utf-8");//设置编码 Result result = reader.decode(binaryBitmap, hints); System.out.println("解析结果为:" + reader.toString()); System.out.println("二维码格式为:"+result.getBarcodeFormat()); System.out.println("二维码文本内容为:"+result.getText()); }catch (Exception ex){
} }}

Barcode4J

  • Barcode4J
    – 纯Java实现的条形码生成
    只负责生成,不负责解析
    – 主要类:
    • BarcodeUtil
    • BarcodeGenerator
    • DefaultConfiguration
      在这里插入图片描述
    Barcode4J 代码示例
    pom.xml引入
net.sf.barcode4j
barcode4j
2.1
org.apache.avalon.framework
avalon-framework-api
4.3.1
Barcode4J 生成一维码代码示例:
package com.torey.javaAdvanced.mooc4.barcode4j;import org.krysalis.barcode4j.impl.code39.Code39Bean;import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;import org.krysalis.barcode4j.tools.UnitConv;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileOutputStream;/** * @ClassName:BarCodeTest * @Description:barcode4j 生成一维码 * @author: Torey */public class BarCodeTest {
public static void main(String[] args){
String msg="1234567891122AAs"; String path="1dcode4j.png"; generateFile(msg,path); } private static void generateFile(String msg, String path) {
File file = new File(path); try{
//Code39 EAN13 都是一维条形码的不同标注 Code39Bean code39Bean = new Code39Bean(); //EAN13Bean ean13Bean = new EAN13Bean(); //dpi精度 像素精度 final int dpi=150; //module宽度 //bean.setModuleWidth(0.2) final double width=UnitConv.in2mm(2.0f/dpi); code39Bean.setWideFactor(3); code39Bean.setModuleWidth(width); code39Bean.doQuietZone(false); String formar="image/png"; //输出到流 BitmapCanvasProvider canvasProvider = new BitmapCanvasProvider(new FileOutputStream(file), formar, dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0); //生成条形码 code39Bean.generateBarcode(canvasProvider,msg); //结束绘制 canvasProvider.finish(); }catch (Exception ex){
ex.printStackTrace(); } }}
Barcode4J 生成二维码代码示例:
package com.torey.javaAdvanced.mooc4.barcode4j;import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import org.apache.avalon.framework.configuration.Configuration;import org.apache.avalon.framework.configuration.DefaultConfiguration;import org.krysalis.barcode4j.BarcodeGenerator;import org.krysalis.barcode4j.BarcodeUtil;import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;import org.krysalis.barcode4j.tools.MimeTypes;/** * @ClassName:DataMatrixCodeTest * @Description: * @author: Torey */public class DataMatrixCodeTest {
public static void main(String[] args) throws Exception {
generateCode("2dcode4j.png","hello ,你好吗?"); }private static void generateCode(String path,String msg){
try{
BarcodeUtil util = BarcodeUtil.getInstance(); BarcodeGenerator gen = util.createBarcodeGenerator(buildCfg("datamatrix")); OutputStream fout = new FileOutputStream("2dcode4j.png"); int resolution = 300; BitmapCanvasProvider canvas = new BitmapCanvasProvider(fout, "image/png", resolution, BufferedImage.TYPE_BYTE_BINARY, false, 0); gen.generateBarcode(canvas, msg); canvas.finish(); }catch (Exception ex){
ex.printStackTrace(); }} private static Configuration buildCfg(String type) {
DefaultConfiguration cfg = new DefaultConfiguration("barcode"); // Bar code type DefaultConfiguration child = new DefaultConfiguration(type); cfg.addChild(child); // Human readable text position DefaultConfiguration attr = new DefaultConfiguration("human-readable");// DefaultConfiguration subAttr = new DefaultConfiguration("placement");// subAttr.setValue("bottom");// attr.addChild(subAttr);// child.addChild(attr);// datamatrix code has no human-readable part// see http://barcode4j.sourceforge.net/2.1/symbol-datamatrix.html attr = new DefaultConfiguration("height"); attr.setValue(50); child.addChild(attr); attr = new DefaultConfiguration("module-width"); attr.setValue("0.6"); child.addChild(attr); return cfg; }}

转载地址:http://gpjj.baihongyu.com/

你可能感兴趣的文章