随笔 - 65  文章 - 0  评论 - 21  阅读 - 32万

【Android QR Code】开源项目: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;
}
复制代码

 

范例项目运行结果:

 

 

posted on   Anthony Li  阅读(6521)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
< 2012年11月 >
28 29 30 31 1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 1
2 3 4 5 6 7 8

博客园博客已停止更新,博客地址:dyinigbleed.com

点击右上角即可分享
微信分享提示