android之二維碼的生成
來源:程序員人生 發(fā)布時(shí)間:2015-04-03 08:23:07 閱讀次數(shù):4001次
2維條碼/2維碼(2-dimensional bar code)是用某種特定的幾何圖形按1定規(guī)律在平面(2維方向上)散布的黑白相間的圖形記錄數(shù)據(jù)符號(hào)信息的;在代碼編制上奇妙地利用構(gòu)成計(jì)算機(jī)內(nèi)部邏輯基礎(chǔ)的“0”、“1”比特流的概念,使用若干個(gè)與2進(jìn)制相對(duì)應(yīng)的幾何形體來表示文字?jǐn)?shù)值信息,通過圖像輸入裝備或光電掃描裝備自動(dòng)識(shí)讀以實(shí)現(xiàn)信息自動(dòng)處理:它具有條碼技術(shù)的1些共性:每種碼制有其特定的字符集;每一個(gè)字符占有1定的寬度;具有1定的校驗(yàn)功能等。同時(shí)還具有對(duì)不同行的信息自動(dòng)辨認(rèn)功能、及處理圖形旋轉(zhuǎn)變化點(diǎn)。
下面就是android2維碼生成的簡(jiǎn)單例子:
(注意要導(dǎo)入ZXing庫(kù),下載地址: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個(gè)imageView控件
sweepIV = (ImageView)findViewById(R.id.imageView1);
CreateQRImageTest imageTest = new CreateQRImageTest();
imageTest.createQRImage("nihao"); ?//輸入要生成的2維碼的字符串
}
//生成2維碼的類
public class CreateQRImageTest
{
//要轉(zhuǎn)換的地址或字符串,可以是中文
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⑻");
//圖象數(shù)據(jù)轉(zhuǎn)換,使用了矩陣轉(zhuǎn)換
BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
//下面這里依照2維碼的算法,逐一生成2維碼的圖片,
//兩個(gè)for循環(huán)是圖片橫列掃描的結(jié)果
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個(gè)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;
}
}
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)