删除二维码外面多余白边
//生成二维码bitmap
public static Bitmap getQrCodeImage(int bitmapWidth, int bitmapHeight, String text) throws WriterException {
//创建Hashtable
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
//设置编码
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//根据text创建BitMatrix
BitMatrix matrix1 = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, bitmapWidth, bitmapHeight);
BitMatrix matrix = deleteWhite(matrix1);
//根据宽高创建像素数组
int width = matrix.getWidth();
int 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] = BLACK;
}else{
pixels[y * width + x] = WHITE;
}
}
}
//创建bitmap
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
//设置像素点
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
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;
}