生成一个带logo的二维码
现在的app基本都会带有生成二维码的功能,为了提现高大上,往往会在二维码的中间加上一个有个性的logo(公司的标志或者app应用的icon).但是这个高大上的需求其实非常容易实现,下面就直接上代码
/**
* 生成二维码
*
* @param string
* 二维码中包含的文本信息
* @param mBitmap
* logo图片
* @param format
* 编码格式BarcodeFormat.QR_CODE
* @return Bitmap 位图
* @throws WriterException
*/
public Bitmap createCode(String string, Bitmap mBitmap, BarcodeFormat format)
throws WriterException {
//往往对logo的大小有要求,所以需要经过压缩处理,压缩比例可以根据自己的需要进行调整,当然,最终的结果是不影响识别率
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);
QRCodeWriter writer = new QRCodeWriter();
Hashtable<EncodeHintType, Object> hst = new Hashtable<EncodeHintType, Object>();
hst.put(EncodeHintType.CHARACTER_SET, "UTF-8");// 设置字符编码
hst.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); //容错率设置高一点
BitMatrix matrix = writer.encode(string, format, 600, 600, hst);// 生成二维码矩阵信息
int width = matrix.getWidth();// 矩阵高度
int height = matrix.getHeight();// 矩阵宽度
//提前拿到二维码的中心点坐标,方便后面logo位置的判断
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;
}
不要忘记加入jar包QRCodeCore.jar.好了,生成带logo的二维码就是这么简单