废话不多说,放码。
private int QR_WIDTH = 230;
private int QR_HEIGHT = 230;
// 二维码logo图片宽度的一半
private int IMAGE_HALFWIDTH = 20;
/**
* 生成二维码 中间插入小图片
*
* @param str 内容
* @return Bitmap
* @throws WriterException
*/
public Bitmap cretaeBitmap(String str, Bitmap icon) throws WriterException {
// 缩放一个40*40的图片
int[] mPixels = new int[2 * IMAGE_HALFWIDTH * 2 * IMAGE_HALFWIDTH];
icon = Untilly.zoomBitmap(icon, IMAGE_HALFWIDTH);
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
BitMatrix matrix = new MultiFormatWriter().encode(str,
BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
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] = icon.getPixel(x - halfW
+ IMAGE_HALFWIDTH, y - halfH + IMAGE_HALFWIDTH);
} else {
if (matrix.get(x, y)) {
pixels[y * width + x] = 0xff000000;
} else { // 无信息设置像素点为白色,或者什么都不设置也行
pixels[y * width + x] = 0xffffffff;
}
}
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
// 通过像素数组生成bitmap
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}