使用ZXing處理二維碼(二)——二維碼生成


[轉]http://blog.csdn.net/dlutbrucezhang/article/details/8582839

注:原文在生成二維碼代碼中漏傳了一個參數,會導致中文亂碼的問題。見下紅色標注。

二維碼的定義:

二維碼 (2-dimensional bar code),是用某種特定的幾何圖形按一定規律在平面(二維方向上)
分布的黑白相間的圖形記錄數據符號信息的。

在許多種類的二維條碼中,常用的碼制有:Data Matrix, Maxi Code, Aztec, QR Code, Vericode, PDF417, Ultracode, Code 49, Code 16K等。
  1.堆疊式/行排式二維條碼,如,Code 16K、Code 49、PDF417(如下圖)等


 
    2.矩陣式二維碼,最流行莫過於QR CODE
二維碼的名稱是相對與一維碼來說的,比如以前的條形碼就是一個“一維碼”,
它的優點有:二維碼存儲的數據量更大;可以包含數字、字符,及中文文本等混合內容;有一定的容錯性(在部分損壞以后可以正常讀取);空間利用率高等。

二維碼原理介紹:

QR(Quick-Response) code是被廣泛使用的一種二維碼,解碼速度快。
它可以存儲多用類型




 
如上圖時一個qrcode的基本結構,其中:
位置探測圖形、位置探測圖形分隔符、定位圖形:用於對二維碼的定位,對每個QR碼來說,位置都是固定存在的,只是大小規格會有所差異;
校正圖形:規格確定,校正圖形的數量和位置也就確定了;
格式信息:表示改二維碼的糾錯級別,分為L、M、Q、H;

版本信息:即二維碼的規格,QR碼符號共有40種規格的矩陣(一般為黑白色),從21x21(版本1),到177x177(版本40),每一版本符號比前一版本 每邊增加4個模塊。
數據和糾錯碼字:實際保存的二維碼信息,和糾錯碼字(用於修正二維碼損壞帶來的錯誤)。

簡要的編碼過程:
    1. 數據分析:確定編碼的字符類型,按相應的字符集轉換成符號字符; 選擇糾錯等級,在規格一定的條件下,糾錯等級越高其真實數據的容量越小。

    2. 數據編碼:將數據字符轉換為位流,每8位一個碼字,整體構成一個數據的碼字序列。其實知道這個數據碼字序列就知道了二維碼的數據內容。
          
 

 
 
            數據可以按照一種模式進行編碼,以便進行更高效的解碼,例如:對數據:01234567編碼(版本1-H),
            1)分組:012 345 67

 

            2)轉成二進制:

012→0000001100

                345→0101011001
                67 →1000011
            3)轉成序列:0000001100 0101011001 1000011
            4)字符數 轉成二進制:8→0000001000
            5)加入模式指示符(上圖數字)0001:0001 0000001000 0000001100 0101011001 1000011
           對於字母、中文、日文等只是分組的方式、模式等內容有所區別。基本方法是一致的

    3. 糾錯編碼:按需要將上面的碼字序列分塊,並根據糾錯等級和分塊的碼字,產生糾錯碼字,並把糾錯碼字加入到數據碼字序列后面,成為一個新的序列。
             

 
        在二維碼規格和糾錯等級確定的情況下,其實它所能容納的碼字總數和糾錯碼字數也就確定了,比如:版本10,糾錯等級時H時,總共能容納346個碼字,其中224個糾錯碼字。
        就是說二維碼區域中大約1/3的碼字時冗余的。對於這224個糾錯碼字,它能夠糾正112個替代錯誤(如黑白顛倒)或者224個據讀錯誤(無法讀到或者無法譯碼),
        這樣糾錯容量為:112/346=32.4%
       
    4. 構造最終數據信息:在規格確定的條件下,將上面產生的序列按次序放如分塊中
        按規定把數據分塊,然后對每一塊進行計算,得出相應的糾錯碼字區塊,把糾錯碼字區塊 按順序構成一個序列,添加到原先的數據碼字序列后面。
        如:D1, D12, D23, D35, D2, D13, D24, D36, ... D11, D22, D33, D45, D34, D46, E1, E23,E45, E67, E2, E24, E46, E68,...

構造矩陣:將探測圖形、分隔符、定位圖形、校正圖形和碼字模塊放入矩陣中。
         

 把上面的完整序列填充到相應規格的二維碼矩陣的區域中

 

    6. 掩摸:將掩摸圖形用於符號的編碼區域,使得二維碼圖形中的深色和淺色(黑色和白色)區域能夠比率最優的分布。
    7. 格式和版本信息:生成格式和版本信息放入相應區域內。
        版本7-40都包含了版本信息,沒有版本信息的全為0。二維碼上兩個位置包含了版本信息,它們是冗余的。
        版本信息共18位,6X3的矩陣,其中6位時數據為,如版本號8,數據位的信息時 001000,后面的12位是糾錯位。
     

二維碼現在隨處可見,使用Android代碼根據輸入的字符串生成二維碼其實也很簡單,其中需要引用一個Google開源的包--ZXing。

下面這個例子里包含條形碼和QR碼的生成和解析,下面講解二維碼的生成。

首先,給出實現的截圖:


 

生成二維碼的步驟如下:

1.首先用戶在編輯框中輸入需要生成的字符串內容

2.點擊下方的按鈕

3.按鈕下方的ImageView控件顯示生成的二維碼

 

下面給出實現的具體代碼:

1.界面的布局

 

[html]  view plain copy print ?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:background="@android:color/white"  
  6.     android:orientation="vertical" >  
  7.   
  8.     <Button  
  9.         android:id="@+id/btn_scan_barcode"  
  10.         android:layout_width="fill_parent"  
  11.         android:layout_height="wrap_content"  
  12.         android:layout_marginTop="30dp"  
  13.         android:text="Open camera" />  
  14.       
  15.     <LinearLayout   
  16.         android:orientation="horizontal"  
  17.         android:layout_marginTop="10dp"  
  18.         android:layout_width="fill_parent"  
  19.         android:layout_height="wrap_content">  
  20.           
  21.         <TextView   
  22.         android:layout_width="wrap_content"  
  23.         android:layout_height="wrap_content"  
  24.         android:textColor="@android:color/black"  
  25.         android:textSize="18sp"  
  26.         android:text="Scan result:" />  
  27.           
  28.         <TextView   
  29.         android:id="@+id/tv_scan_result"  
  30.         android:layout_width="fill_parent"  
  31.         android:textSize="18sp"  
  32.         android:textColor="@android:color/black"  
  33.         android:layout_height="wrap_content" />  
  34.     </LinearLayout>  
  35.       
  36.     <EditText   
  37.         android:id="@+id/et_qr_string"  
  38.         android:layout_width="fill_parent"  
  39.         android:layout_height="wrap_content"  
  40.         android:layout_marginTop="30dp"  
  41.         android:hint="Input the text"/>  
  42.       
  43.     <Button  
  44.         android:id="@+id/btn_add_qrcode"  
  45.         android:layout_width="fill_parent"  
  46.         android:layout_height="wrap_content"  
  47.         android:text="Generate QRcode" />  
  48.       
  49.     <ImageView   
  50.         android:id="@+id/iv_qr_image"  
  51.         android:layout_width="wrap_content"  
  52.         android:layout_height="wrap_content"  
  53.         android:layout_marginTop="10dp"  
  54.         android:layout_gravity="center"/>  
  55.   
  56. </LinearLayout>  


2.生成二維碼的代碼

 

 

[java]  view plain copy print ?
  1. package com.zxing.encoding;  
  2.   
  3. import java.util.Hashtable;  
  4.   
  5. import android.graphics.Bitmap;  
  6.   
  7. import com.google.zxing.BarcodeFormat;  
  8. import com.google.zxing.EncodeHintType;  
  9. import com.google.zxing.MultiFormatWriter;  
  10. import com.google.zxing.WriterException;  
  11. import com.google.zxing.common.BitMatrix;  
  12. /** 
  13.  * @author Ryan Tang 
  14.  * 
  15.  */  
  16. public final class EncodingHandler {  
  17.     private static final int BLACK = 0xff000000;  
  18.       
  19.     public static Bitmap createQRCode(String str,int widthAndHeight) throws WriterException {  
  20.         Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();    
  21.         hints.put(EncodeHintType.CHARACTER_SET, "utf-8");   
  22.         BitMatrix matrix = new MultiFormatWriter().encode(str,  
  23.                 BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight,hints);  
  24.         int width = matrix.getWidth();  
  25.         int height = matrix.getHeight();  
  26.         int[] pixels = new int[width * height];  
  27.           
  28.         for (int y = 0; y < height; y++) {  
  29.             for (int x = 0; x < width; x++) {  
  30.                 if (matrix.get(x, y)) {  
  31.                     pixels[y * width + x] = BLACK;  
  32.                 }  
  33.             }  
  34.         }  
  35.         Bitmap bitmap = Bitmap.createBitmap(width, height,  
  36.                 Bitmap.Config.ARGB_8888);  
  37.         bitmap.setPixels(pixels, 0, width, 00, width, height);  
  38.         return bitmap;  
  39.     }  
  40. }  


3.Activity上的操作實現

 

 

[java]  view plain copy print ?
  1. package com.ericssonlabs;  
  2.   
  3. import com.google.zxing.WriterException;  
  4. import com.zxing.activity.CaptureActivity;  
  5. import com.zxing.encoding.EncodingHandler;  
  6.   
  7. import android.app.Activity;  
  8. import android.content.Intent;  
  9. import android.graphics.Bitmap;  
  10. import android.os.Bundle;  
  11. import android.view.View;  
  12. import android.view.View.OnClickListener;  
  13. import android.widget.Button;  
  14. import android.widget.EditText;  
  15. import android.widget.ImageView;  
  16. import android.widget.TextView;  
  17. import android.widget.Toast;  
  18.   
  19. public class BarCodeTestActivity extends Activity {  
  20.     /** Called when the activity is first created. */  
  21.     private TextView resultTextView;  
  22.     private EditText qrStrEditText;  
  23.     private ImageView qrImgImageView;  
  24.       
  25.     @Override  
  26.     public void onCreate(Bundle savedInstanceState) {  
  27.         super.onCreate(savedInstanceState);  
  28.         setContentView(R.layout.main);  
  29.           
  30.         resultTextView = (TextView) this.findViewById(R.id.tv_scan_result);  
  31.         qrStrEditText = (EditText) this.findViewById(R.id.et_qr_string);  
  32.         qrImgImageView = (ImageView) this.findViewById(R.id.iv_qr_image);  
  33.           
  34.         Button scanBarCodeButton = (Button) this.findViewById(R.id.btn_scan_barcode);  
  35.         scanBarCodeButton.setOnClickListener(new OnClickListener() {  
  36.               
  37.             @Override  
  38.             public void onClick(View v) {  
  39.                 Intent openCameraIntent = new Intent(BarCodeTestActivity.this,CaptureActivity.class);  
  40.                 startActivityForResult(openCameraIntent, 0);  
  41.             }  
  42.         });  
  43.           
  44.         Button generateQRCodeButton = (Button) this.findViewById(R.id.btn_add_qrcode);  
  45.         generateQRCodeButton.setOnClickListener(new OnClickListener() {  
  46.               
  47.             @Override  
  48.             public void onClick(View v) {  
  49.                 try {  
  50.                     String contentString = qrStrEditText.getText().toString();  
  51.                     if (!contentString.equals("")) {  
  52.                         Bitmap qrCodeBitmap = EncodingHandler.createQRCode(contentString, 350);  
  53.                         qrImgImageView.setImageBitmap(qrCodeBitmap);  
  54.                     }else {  
  55.                         Toast.makeText(BarCodeTestActivity.this"Text can not be empty", Toast.LENGTH_SHORT).show();  
  56.                     }  
  57.                       
  58.                 } catch (WriterException e) {  
  59.                     // TODO Auto-generated catch block  
  60.                     e.printStackTrace();  
  61.                 }  
  62.             }  
  63.         });  
  64.     }  
  65.   
  66.     @Override  
  67.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  68.         super.onActivityResult(requestCode, resultCode, data);  
  69.         if (resultCode == RESULT_OK) {  
  70.             Bundle bundle = data.getExtras();  
  71.             String scanResult = bundle.getString("result");  
  72.             resultTextView.setText(scanResult);  
  73.         }  
  74.     }  
  75. }  


下面給出Demo的下載地址:

 

http://download.csdn.net/detail/dlutbrucezhang/5066053


免責聲明!

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



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