有的应用需要将一段字符串加密为一个二维码,我们可以用一个现成的开源框架来帮我们搞定二维码,这个框架就是Google 自家的Zxing
它已经封装好了对一维码、二维码的编码和解码的功能。
如何使用Zxing将一个字符串转换为二维码位图呢?
我们来看以下代码:
static Bitmap encodeAsBitmap(String contents, BarcodeFormat format,
int desiredWidth, int desiredHeight) throws WriterException {
final int WHITE = 0xFFFFFFFF; //可以指定其他颜色,让二维码变成彩色效果
final int BLACK = 0xFF000000;
HashMap<EncodeHintType, String> hints = null;
String encoding = guessAppropriateEncoding(contents);
if (encoding != null) {
hints = new HashMap<EncodeHintType, String>(2);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result = writer.encode(contents, format, desiredWidth,
desiredHeight, hints);
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
// All are 0, or black, by default
for (int y = 0; y < height; y++) {//这个用于填充二维码“像素点”矩阵,我们要用一个双重循环来将result中的点将(x,y)中一个一个取出来,放到pixels[]里
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);//组合生成二维码位图,把pixels数组转换成位图
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
private static String guessAppropriateEncoding(CharSequence contents) {
// 手动判断所给字符序列是否为utf-8编码,如果是,返回utf-8,用于指定二维码编码时的编码类型
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) {
return "UTF-8";
}
}
return null;
}
最后保存到文件:
bitmap = encodeAsBitmap(content, BarcodeFormat.QR_CODE, desiredWidth, desiredHeight);
if(null != bitmap) {//将二维码图像保存到文件
File file = new File(Environment.getExternalStorageDirectory(), imageFileName);
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 0, fos);
}