android之二維碼的生成
來源:程序員人生 發布時間:2015-04-03 08:23:07 閱讀次數:4010次
2維條碼/2維碼(2-dimensional bar code)是用某種特定的幾何圖形按1定規律在平面(2維方向上)散布的黑白相間的圖形記錄數據符號信息的;在代碼編制上奇妙地利用構成計算機內部邏輯基礎的“0”、“1”比特流的概念,使用若干個與2進制相對應的幾何形體來表示文字數值信息,通過圖像輸入裝備或光電掃描裝備自動識讀以實現信息自動處理:它具有條碼技術的1些共性:每種碼制有其特定的字符集;每一個字符占有1定的寬度;具有1定的校驗功能等。同時還具有對不同行的信息自動辨認功能、及處理圖形旋轉變化點。
下面就是android2維碼生成的簡單例子:
(注意要導入ZXing庫,下載地址:http://pan.baidu.com/s/1o6idVU6)
package com.example.two_dimensional_test1;
import java.util.Hashtable;
import android.graphics.Bitmap;
import android.widget.ImageView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
private ImageView sweepIV;
private int QR_WIDTH = 200, QR_HEIGHT = 200;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//這里就是1個imageView控件
sweepIV = (ImageView)findViewById(R.id.imageView1);
CreateQRImageTest imageTest = new CreateQRImageTest();
imageTest.createQRImage("nihao"); ?//輸入要生成的2維碼的字符串
}
//生成2維碼的類
public class CreateQRImageTest
{
//要轉換的地址或字符串,可以是中文
public void createQRImage(String url)
{
try
{
//判斷URL合法性
if (url == null || "".equals(url) || url.length() < 1)
{
return;
}
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "utf⑻");
//圖象數據轉換,使用了矩陣轉換
BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
//下面這里依照2維碼的算法,逐一生成2維碼的圖片,
//兩個for循環是圖片橫列掃描的結果
for (int y = 0; y < QR_HEIGHT; y++)
{
for (int x = 0; x < QR_WIDTH; x++)
{
if (bitMatrix.get(x, y))
{
pixels[y * QR_WIDTH + x] = 0xff000000;
}
else
{
pixels[y * QR_WIDTH + x] = 0xffffffff;
}
}
}
//生成2維碼圖片的格式,使用ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
//顯示到1個ImageView上面
sweepIV.setImageBitmap(bitmap);
}
catch (WriterException e)
{
e.printStackTrace();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈