Java 條形碼 二維碼 的生成與解析


Barcode簡介

  Barcode是由一組按一定編碼規則排列的條,空符號,用以表示一定的字符,數字及符號組成的,一種機器可讀的數據表示方式。
  Barcode的形式多種多樣,按照它們的外觀分類:
    Linear barcode(一維碼):它的信息存儲量小,僅能存儲一個代號,使用時通過這個代號調取計算機網絡中的數據。
    Matrix barcode(二維碼)。二維碼是近幾年發展起來的,它能在有限的空間內存儲更多的信息,包括文字、圖象、指紋、簽名等,並可脫離計算機使用。
  你可能認為你對它們都有所了解,因為它們大概都是這個樣子的:

       

  但事實上,它們有甚至有可能是這樣子的:

       

  我們通常所說的二維碼,只是Matrix barcode的一種,叫做QR code。

  Barcode種類繁多,有些編碼格式並不常用,即使是ZXing也沒有做到所有格式的支持,開發者只需了解就好。
  其中包括:
  一維條碼編碼格式:
    Code39碼(標准39碼)、Codabar碼(庫德巴碼)、Code25碼(標准25碼)、ITF25碼(交叉25碼)、Matrix25碼(矩陣25碼)、UPC-A碼、UPC-E碼、
    EAN-13碼(EAN-13國際商品條碼)、EAN-8碼(EAN-8國際商品條碼)、中國郵政碼(矩陣25碼的一種變體)、Code-B碼、MSI碼、Code11碼、Code93碼、ISBN碼、ISSN碼、
    Code128碼(Code128碼,包括EAN128碼)、Code39EMS(EMS專用的39碼)等
  二維條碼編碼格式:
    PDF417碼、Code49碼、Code 16k碼、Date Matrix碼、MaxiCode碼(包括 QR Code碼)等。

      Code 39、Code 128、EAN、UPC、QR Code是我們生活中能經常見到的幾種編碼格式,同時ZXing對幾種格式都有比較好的支持。
      其中,UPC-A是一種國際通用的編碼格式,由12個數字構成,EAN-13是在UPC-A基礎上的一種擴充(多了一個數字)。快數一數你身邊的薯片的編碼是不是13位!如果是的話,它最前邊的兩個數字是不是“69”?

      在EAN-13的編碼體系中,前三位數字表示商品生產商的國家(並不是商品所屬公司的國家),中國的編碼是690~699,美國是(000~019、030~039、060~139),日本是(450~459、490~499),and so on。
      不同的編碼格式通常用在不同的領域,如果你看到了一個Code 39或者Code 128的Barcode,那么這很就可能是一個快遞編碼,這個時候你就可以去那些提供快遞查詢的網站查詢一下你的快遞信息,如果有API提供出來那就更是再好不過了。
      至於QR Code,就是我們經常用手機掃一掃的二維碼,表示的信息更是多種多樣,並不僅僅是一個url那么簡單,至於這些信息如何處理,是我們一會兒將要討論的內容。

 

一、google的zxing(jar包下載)

  1:條形碼的生成與解碼(生成的條形碼不顯示 本身的條碼含義,即:條碼下方沒有數字字母等。如有需要,自行拼接)

  

  
 1 import java.awt.image.BufferedImage;
 2 import java.io.File;
 3 import java.io.FileOutputStream;
 4 
 5 import javax.imageio.ImageIO;
 6 
 7 import com.google.zxing.BarcodeFormat;
 8 import com.google.zxing.BinaryBitmap;
 9 import com.google.zxing.LuminanceSource;
10 import com.google.zxing.MultiFormatReader;
11 import com.google.zxing.MultiFormatWriter;
12 import com.google.zxing.Result;
13 import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
14 import com.google.zxing.client.j2se.MatrixToImageWriter;
15 import com.google.zxing.common.BitMatrix;
16 import com.google.zxing.common.HybridBinarizer;
17 
18 public class ZxingEAN13Code {
19     /**
20      * 條形碼編碼
21      * @param contents
22      * @param width
23      * @param height
24      * @param imgPath
25      */
26     public void encode(String contents, int width, int height, String imgPath) {
27         //保證最小為70*25的大小
28         int codeWidth = Math.max(70, width);
29         int codeHeight = Math.max(25, height);
30         try {
31             //使用EAN_13編碼格式進行編碼
32             BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
33                     BarcodeFormat.EAN_13, codeWidth, codeHeight, null);
34             //生成png格式的圖片保存到imgPath路徑
35             MatrixToImageWriter.writeToStream(bitMatrix, "png",
36                     new FileOutputStream(imgPath));
37             System.out.println("encode success! the img's path is "+imgPath);
38         } catch (Exception e) {
39             e.printStackTrace();
40         }
41     }
42 
43     /**
44      * 解析條形碼
45      * @param imgPath
46      * @return
47      */
48     public String decode(String imgPath) {
49         BufferedImage image = null;
50         Result result = null;
51         try {
52             image = ImageIO.read(new File(imgPath));
53             if (image == null) {
54                 System.out.println("the decode image may be not exit.");
55             }
56             LuminanceSource source = new BufferedImageLuminanceSource(image);
57             BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
58 
59             result = new MultiFormatReader().decode(bitmap, null);
60             return result.getText();
61         } catch (Exception e) {
62             e.printStackTrace();
63         }
64         return null;
65     }
66 
67     public static void main(String[] args) {
68         String decodeImgPath = "D:/1.png";
69         ZxingEAN13Code EAN13Code = new ZxingEAN13Code();
70         System.out.println(EAN13Code.decode(decodeImgPath));
71         
72         String encodeImgPath = "D:/2.png";
73         String contents = "6923450657713";
74         int width = 150, height = 40;
75         EAN13Code.encode(contents, width, height, encodeImgPath);
76     }
77 }
View Code

 

  2:在web項目中很少會用到解碼,一般而言是生成條形碼后顯示到頁面或者打印出來,使用掃碼槍掃碼出來條形碼的信息進行進一步的處理

    在此說明:掃碼槍掃描條形碼很簡單,其實就可以把掃碼槍理解成鍵盤,掃描條形碼后,就可以將條碼中的信息(如:6923450657713)顯示在光標定位的地方

  

  
 1 import java.awt.image.BufferedImage;
 2 import java.io.File;
 3 import java.io.IOException;
 4 import java.util.Hashtable;
 5 
 6 import javax.imageio.ImageIO;
 7 import javax.servlet.ServletOutputStream;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 import org.apache.struts.action.ActionForm;
12 import org.apache.struts.action.ActionMapping;
13 
14 import com.google.zxing.BarcodeFormat;
15 import com.google.zxing.EncodeHintType;
16 import com.google.zxing.MultiFormatWriter;
17 import com.google.zxing.WriterException;
18 import com.google.zxing.client.j2se.MatrixToImageWriter;
19 import com.google.zxing.common.BitMatrix;
20 
21 public class ZxingBarCodeUtil {
22     /**
23      * 根據字符串生成條形碼
24      * 
25      * @param code字符串
26      * @return
27      */
28     public static BitMatrix getShapeCode(String code) {
29         // 編碼條形碼
30         Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
31         hints.put(EncodeHintType.CHARACTER_SET, "GBK");
32         BitMatrix matrix = null;
33         try {
34             // 使用code_128格式進行編碼生成100*25的條形碼
35             matrix = new MultiFormatWriter().encode(code,
36                     BarcodeFormat.CODE_128, 100, 25, hints);
37         } catch (WriterException e) {
38             e.printStackTrace();
39         }
40         return matrix;
41     }
42 
43     /** 獲取條形碼 */
44     public void getShapeCode(ActionMapping mapping, ActionForm form,
45             HttpServletRequest request, HttpServletResponse response) {
46         BitMatrix matrix = this.getShapeCode(request.getParameter("printCode"));
47         // 返回png圖片流
48         // 獲得Servlet輸出流
49         ServletOutputStream outStream = null;
50         try {
51             outStream = response.getOutputStream();
52             ImageIO.write(MatrixToImageWriter.toBufferedImage(matrix), "png",
53                     outStream);
54             outStream.flush();
55             // 關閉輸出流
56             outStream.close();
57         } catch (IOException e) {
58             String simplename = e.getClass().getSimpleName();
59             if (!"ClientAbortException".equals(simplename)) {
60                 e.printStackTrace();
61             }
62         }
63     }
64 
65     /*public static void main(String[] args) {
66         BufferedImage buff = MatrixToImageWriter
67                 .toBufferedImage(getShapeCode("TG201603280003"));// 123
68         try {
69             ImageIO.write(buff, "png", new File("D://1.png"));
70             System.out.println("已生成");
71         } catch (IOException e) {
72             e.printStackTrace();
73         }
74     }*/
75 }
View Code

 

 

  3:二維碼的生成與解碼

 

  
 1 import java.awt.image.BufferedImage;
 2 import java.io.File;
 3 import java.io.FileOutputStream;
 4 import java.util.Hashtable;
 5 
 6 import javax.imageio.ImageIO;
 7 
 8 import com.google.zxing.BarcodeFormat;
 9 import com.google.zxing.BinaryBitmap;
10 import com.google.zxing.DecodeHintType;
11 import com.google.zxing.EncodeHintType;
12 import com.google.zxing.LuminanceSource;
13 import com.google.zxing.MultiFormatReader;
14 import com.google.zxing.MultiFormatWriter;
15 import com.google.zxing.Result;
16 import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
17 import com.google.zxing.client.j2se.MatrixToImageWriter;
18 import com.google.zxing.common.BitMatrix;
19 import com.google.zxing.common.HybridBinarizer;
20 import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
21 
22 /**
23  * 二維碼生成/解碼器
24  */
25 public class ZxingQRCode {
26 
27     /**
28      * 生成二維碼
29      * @param contents
30      * @param width
31      * @param height
32      * @param imgPath
33      */
34     public void encode(String contents, int width, int height, String imgPath) {
35         Hashtable<EncodeHintType, Object> hints = new Hashtable();
36         // 指定糾錯等級
37         hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
38         // 指定顯示格式為GBK
39         hints.put(EncodeHintType.CHARACTER_SET, "GBK");
40         try {
41             BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
42                     BarcodeFormat.QR_CODE, width, height, hints);
43             //生成png格式的圖片保存到imgPath路徑位置
44             MatrixToImageWriter.writeToStream(bitMatrix, "png",
45                     new FileOutputStream(imgPath));
46             System.out.println("QR Code encode sucsess! the img's path is "+imgPath);
47         } catch (Exception e) {
48             e.printStackTrace();
49         }
50     }
51 
52     /**
53      * 解析二維碼
54      * @param imgPath
55      * @return
56      */
57     public String decode(String imgPath) {
58         BufferedImage image = null;
59         Result result = null;
60         try {
61             //讀取圖片
62             image = ImageIO.read(new File(imgPath));
63             if (image == null) {
64                 System.out.println("the decode image may be not exit.");
65             }
66             LuminanceSource source = new BufferedImageLuminanceSource(image);
67             BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
68 
69             Hashtable<DecodeHintType, Object> hints = new Hashtable();
70             //設置顯示格式為GBK
71             hints.put(DecodeHintType.CHARACTER_SET, "GBK");
72             //進行解碼
73             result = new MultiFormatReader().decode(bitmap, hints);
74             return result.getText();//返回結果信息
75         } catch (Exception e) {
76             e.printStackTrace();
77         }
78         return null;
79     }
80 
81     public static void main(String[] args) {
82         ZxingQRCode ORCode = new ZxingQRCode();
83         ORCode.encode("http://www.cnblogs.com/zhaoyhBlog/", 150, 150,
84                 "D:/二維碼1.png");
85 
86         System.out.println(ORCode.decode("D:/二維碼1.png"));
87     }
88 }
View Code

 

 二、使用org.jbarcode(jar包下載)

1、生成條形碼(條形碼下方包含  本身的含義,即:條碼下方有數字字母等)

 1 import java.awt.image.BufferedImage;
 2 import java.io.FileOutputStream;
 3 import org.jbarcode.JBarcode;
 4 import org.jbarcode.encode.EAN8Encoder;
 5 import org.jbarcode.paint.EAN8TextPainter;
 6 import org.jbarcode.paint.WidthCodedPainter;
 7 import org.jbarcode.util.ImageUtil;
 8 
 9 /**
10  * 支持EAN13, EAN8, UPCA, UPCE, Code 3 of 9, Codabar, Code 11, Code 93, Code 128,
11  * MSI/Plessey, Interleaved 2 of PostNet等
12  */
13 public class JBarcodeByEAN8Util {
14 
15     public void encodeByEAN8(String content, String imgPath, int with,
16             int height) {
17         try {
18             JBarcode jBarcode = new JBarcode(EAN8Encoder.getInstance(),
19                     WidthCodedPainter.getInstance(), EAN8TextPainter.getInstance());
20             BufferedImage bufferedImage = jBarcode.createBarcode(content);
21             FileOutputStream outputStream = new FileOutputStream(imgPath);
22             ImageUtil.encodeAndWrite(bufferedImage, "jpeg", outputStream, with,height);
23             outputStream.close();
24             System.out.println("===");
25         } catch (Exception localException) {
26             localException.printStackTrace();
27         }
28     }
29 
30     public static void main(String[] paramArrayOfString) {
31         JBarcodeByEAN8Util jBarCodeUtil = new JBarcodeByEAN8Util();
32         jBarCodeUtil.encodeByEAN8("110120119", "D:/EAN8.jpg", 100, 70);
33     }
34 }
View Code

 

 

 

 

 

參考鏈接:http://www.oschina.net/code/snippet_170632_47382

    http://www.oschina.net/code/snippet_152736_10891


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM