博主声明:
转载请在开头附加本文链接及作者信息,并标记为转载。本文由博主 威威喵 原创,请多支持与指教。
二维码,这个在现在出门支付必备的支付方式,到哪里都是微信、支付宝扫一扫支付。确实是时代的进步,科技的进步,我们现在才得以如此方便。现在的安卓应用,应该都离不开二维码,比如:名片二维码,登入二维码,支付二维码等等,还有小单车二维码解锁,这些都体现了二维码技术带来的方便。
接下来,我来介绍一下安卓端的二维码技术。首先,我们依赖一个ZXing库,这个库里面已经封装好了一些二维码生成工具,我们用起来很方便。我们生成二维码的图:
-
使用
这里我们通过代码来演示一下怎么生成二维码:(我已经封装好这个类,直接使用即可)
/**
* 生成二维码工具类
*
* @Created by xww.
* @Creation time 2018/8/31.
*/
public final class QRCodeUtil {
/**
* @param content 二维码存放的内容
* @param width 二维码图片宽度
* @param height 二维码图片高度
* @return Bitmap对象,使用ImageView显示即可
*/
public static Bitmap createQRCode(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;
}
/**
* 解析二维码,得到内容
*/
public static String deCodeQR(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result = null;
QRCodeReader reader = new QRCodeReader();
try {
result = reader.decode(binaryBitmap);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (ChecksumException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
}
return result.getText();
}
}
这个工具类就很方便了,我们创建二维码,只需要这样调用:
bitmapQRCode = QRCodeUtil.createQRCode("TestQRCode", 300, 300);
iv_show_image.setImageBitmap(bitmapQRCode);
要想解析二维码,就这样:
String QRCodeContent = QRCodeUtil.deCodeQR(bitmapQRCode);
Toast.makeText(this, "" + QRCodeContent, Toast.LENGTH_SHORT).show();