准备工作:添加依赖库core.jar
在Package Explorer选择导入的项目,右键 -> Build Path -> Add External Archives...
1、设置编码内容使用的字符集
Map<EncodeHintType,Object> hints = new EnumMap<EncodeHintType,Object>(EncodeHintType.class); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); message = convertToUTF8(message);
2、编码
BitMatrix lBitMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.QR_CODE, 200, 200, hints);
类MultiFormatWriter:This is a factory class which finds the appropriate Writer subclass for the BarcodeFormat requested and encodes the barcode with the supplied contents.
调用encode方法编码,返回一个BitMatrix对象。
类BitMatrix:Represents a 2D matrix of bits. In function arguments below, and throughout the common module, x is the column position, and y is the row position. The ordering is always x, y. The origin is at the top-left. Internally the bits are represented in a 1-D array of 32-bit ints. However, each row begins with a new int. This is done intentionally so that we can copy out a row into a BitArray very efficiently. The ordering of bits is row-major. Within each int, the least significant bits are used first, meaning they represent lower x values. This is compatible with BitArray's implementation.
lBitMatrix仅仅是通过bit来存储二维码数据。如果要更直观地观察编码的结果,我们需要利用lBitMatrix来生成图片。
3、生成图片
首先,我们定义黑色和白色的像素值
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
然后,根据BitMatrix对象,二维矩阵的值,生成图片
private Bitmap toBitmap(BitMatrix bitMatrix) { int width = bitMatrix.getWidth(); int height = bitMatrix.getHeight(); 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] = bitMatrix.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; }
范例项目运行结果: