1.生成二维码
/**
* 生成二维码
*
* @param contents 内容
* @param width
* @param height
* @return 返回Bitmap对象
* @throws WriterException
*/
public static Bitmap encodeAsBitmap(String contents, int width, int height) {
try {
String contentsToEncode = contents;
if (contentsToEncode == null) {
return null;
}
Map<EncodeHintType, Object> hints = null;
String encoding = "utf-8";
if (encoding != null) {
hints = new EnumMap<>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
BitMatrix result;
result = new MultiFormatWriter().encode(contentsToEncode, BarcodeFormat.QR_CODE, width, height, hints);
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
} catch (WriterException e) {
e.printStackTrace();
return null;
}
}
这个方法可以在https://github.com/zxing/zxing 中/android/src/com/google/zxing/client/android/encode/QRCodeEncoder.java文件里可以直接考过来直接用稍微改一下就ok了
2.解析二维码
/**
* 解析二维码
* @param bitmap
* @return
*/
public static String parseQRBitmap(Bitmap bitmap){
QRCodeMultiReader qrCodeMultiReader=new QRCodeMultiReader();
int[] data = new int[bitmap.getWidth() * bitmap.getHeight()];
bitmap.getPixels(data,0,bitmap.getWidth(),0,0,bitmap.getWidth(),bitmap.getHeight());
RGBLuminanceSource source=new RGBLuminanceSource(bitmap.getWidth(),bitmap.getHeight(),data);
BinaryBitmap binaryBitmap=new BinaryBitmap(new HybridBinarizer(source));
Hashtable<DecodeHintType,String> hints=new Hashtable<>();
hints.put(DecodeHintType.CHARACTER_SET,"utf-8");
try {
return qrCodeMultiReader.decode(binaryBitmap,hints).getText();
} catch (NotFoundException e) {
e.printStackTrace();
} catch (ChecksumException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
}
return null;
}
最后附上运行结果