使用zxing生成二維碼工具類
阿新 • • 發佈:2018-12-10
public class QRCodeUtils {
/**
* 建立二維碼(有白邊)
*
* @param string
* @return
*/
public static Bitmap createQRCode(String string, int width, int height) {
return createQRCode(string, width, height, false);
}
/**
* 建立二維碼(無白邊)
*
* @param string
* @param width
* @param height
* @return
*/
public static Bitmap createQRCodeNoWhiteBorder(String string, int width, int height) {
return createQRCode(string, width, height, true);
}
/**
* 建立二維碼
*
* @param string
* @param width
* @param height
* @param isDelWhiteBorder
* @return
*/
private static Bitmap createQRCode(String string, int width, int height, boolean isDelWhiteBorder) {
try {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8" );
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix matrix = new QRCodeWriter().encode(string, BarcodeFormat.QR_CODE, width, height);
if (isDelWhiteBorder) {
matrix = deleteWhite(matrix);//刪除白邊
}
width = matrix.getWidth();
height = matrix.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (matrix.get(x, y)) {
// pixels[y * width + x] = Color.TRANSPARENT;
// 設定二維碼顏色 順序是 左上 右上 左下 右下
if (x < width / 2 && y < height / 2) {
pixels[y * width + x] = 0xFF0094FF;// 藍色
Integer.toHexString(new Random().nextInt());
} else if (x > width / 2 && y < height / 2) {
pixels[y * width + x] = Color.CYAN;// 青色
} else if (x < width / 2 && y > height / 2) {
pixels[y * width + x] = 0xFFFED545;// 黃色
} else if (x > width / 2 && y > height / 2) {
pixels[y * width + x] = 0xFF5ACF00;// 綠色
} else {
// pixels[y * width + x] = Color.BLACK;// 黑色
pixels[y * width + x] = Color.TRANSPARENT;// 透明
}
//pixels[y * width + x] = Color.BLACK;
} else {
//pixels[y * width + x] = Color.WHITE;//白色
pixels[y * width + x] = Color.TRANSPARENT;// 透明
}
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
} catch (Exception e) {
return null;
}
}
/**
* 刪除二維碼生成後的白色邊框
*
* @param matrix
* @return
*/
private static BitMatrix deleteWhite(BitMatrix matrix) {
int[] rec = matrix.getEnclosingRectangle();
int resWidth = rec[2] + 1;
int resHeight = rec[3] + 1;
BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
resMatrix.clear();
for (int i = 0; i < resWidth; i++) {
for (int j = 0; j < resHeight; j++) {
if (matrix.get(i + rec[0], j + rec[1]))
resMatrix.set(i, j);
}
}
return resMatrix;
}
}