二维码,相信大家有不陌生,现在主流的app,例如微信支付宝等等,几乎都会有二维码的功能,所谓是非常之广泛。
二维码分为2个部分,一个是生成,一个是识别,这里我们先来讲讲二维码是如何生成的。
二维码的开发使用我们大多都是使用Google提供的zxing这个类库,使用这个类库我们需要先下载核心jar包,jar包下载地址,如果我们只想生成二维码那么这个就够了。
下载之后添加:
看代码:
/**
* 生成二维码图片
*/
private Bitmap generateBitmap(String content,int width, int height) {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
Map<EncodeHintType, String> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
try {
BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
int[] pixels = new int[width * height];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (encode.get(j, i)) {
pixels[i * width + j] = 0x00000000;
} else {
pixels[i * width + j] = 0xffffffff;
}
}
}
return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
/**
* 给二维码中间加logo图片
*
* @param qrBitmap 二维码图片
* @param logoBitmap logo图片
* @return
*/
public static Bitmap addLogo(Bitmap qrBitmap, Bitmap logoBitmap) {
int qrBitmapWidth = qrBitmap.getWidth();
int qrBitmapHeight = qrBitmap.getHeight();
int logoBitmapWidth = logoBitmap.getWidth();
int logoBitmapHeight = logoBitmap.getHeight();
Bitmap blankBitmap = Bitmap.createBitmap(qrBitmapWidth, qrBitmapHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(blankBitmap);
canvas.drawBitmap(qrBitmap, 0, 0, null);
canvas.save(Canvas.ALL_SAVE_FLAG);
float scaleSize = 1.0f;
while ((logoBitmapWidth / scaleSize) > (qrBitmapWidth / 5) || (logoBitmapHeight / scaleSize) > (qrBitmapHeight / 5)) {
scaleSize *= 2;
}
float sx = 1.0f / scaleSize;
canvas.scale(sx, sx, qrBitmapWidth / 2, qrBitmapHeight / 2);
canvas.drawBitmap(logoBitmap, (qrBitmapWidth - logoBitmapWidth) / 2, (qrBitmapHeight - logoBitmapHeight) / 2, null);
canvas.restore();
return blankBitmap;
}