开源项目:ZXing(二)二维码编码

准备工作:添加依赖库core.jar

在Package Explorer选择导入的项目,右键 -> Build Path -> Add External Archives...

选择zxing/core目录下的core.jar

 

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;
}
复制代码

 

范例项目运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值