參考:http://blog.csdn.net/jdsjlzx/article/details/45969003
依賴於Google開源框架zxing
下載core.jar http://maven.outofmemory.cn/com.google.zxing/core/3.1.0/
普通二維碼
<span style="white-space:pre"> </span>/*
* url:掃描文本信息 width:生成二維碼寬 height:高
*/
public Bitmap createQRImage(String url, final int width, final int height) {
try {
// 判斷URL合法性
if (url == null || "".equals(url) || url.length() < 1) {
return null;
}
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 圖像數據轉換,使用了矩陣轉換
BitMatrix bitMatrix = new QRCodeWriter().encode(url,
BarcodeFormat.QR_CODE, width, height, hints);
int[] pixels = new int[width * height];
// 下面這裏按照二維碼的算法,逐個生成二維碼的圖片,
// 兩個for循環是圖片橫列掃描的結果
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * width + x] = 0xff000000;
} else {
pixels[y * width + x] = 0xffffffff;
}
}
}
// 生成二維碼圖片的格式,使用ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
生成帶圖片的二維碼
圖片像素不能太高,若要大些,相應的二維碼尺寸也要增大,否則無法識別,不能被掃描出來
private int IMAGE_HALFWIDTH = 10;// 中間圖片的寬度
/*
* string:文本信息
* mBitmap:要插入的圖片
*/
public Bitmap createCode(String string, Bitmap mBitmap, BarcodeFormat format)
throws WriterException {
Matrix m = new Matrix();
float sx = (float) 2 * IMAGE_HALFWIDTH / mBitmap.getWidth();
float sy = (float) 2 * IMAGE_HALFWIDTH / mBitmap.getHeight();
m.setScale(sx, sy);// 設置縮放信息
// 將logo圖片按martix設置的信息縮放
mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(),
mBitmap.getHeight(), m, false);
MultiFormatWriter writer = new MultiFormatWriter();
Hashtable<EncodeHintType, String> hst = new Hashtable<EncodeHintType, String>();
hst.put(EncodeHintType.CHARACTER_SET, "UTF-8");// 設置字符編碼
BitMatrix matrix = writer.encode(string, format, 400, 400, hst);// 生成二維碼矩陣信息
int width = matrix.getWidth();// 矩陣高度
int height = matrix.getHeight();// 矩陣寬度
int halfW = width / 2;
int halfH = height / 2;
int[] pixels = new int[width * height];// 定義數組長度爲矩陣高度*矩陣寬度,用於記錄矩陣中像素信息
for (int y = 0; y < height; y++) {// 從行開始迭代矩陣
for (int x = 0; x < width; x++) {// 迭代列
if (x > halfW - IMAGE_HALFWIDTH && x < halfW + IMAGE_HALFWIDTH
&& y > halfH - IMAGE_HALFWIDTH
&& y < halfH + IMAGE_HALFWIDTH) {// 該位置用於存放圖片信息
// 記錄圖片每個像素信息
pixels[y * width + x] = mBitmap.getPixel(x - halfW
+ IMAGE_HALFWIDTH, y - halfH + IMAGE_HALFWIDTH);
} else {
if (matrix.get(x, y)) {// 如果有黑塊點,記錄信息
pixels[y * width + x] = 0xff000000;// 記錄黑塊信息
}
}
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
// 通過像素數組生成bitmap
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}