【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; }
范例项目运行结果:
iOS 开发讨论群:82873648

本作品采用知识共享署名-非商业性使用 3.0 许可协议进行许可。
转载请署名李震(博客地址:http://www.cnblogs.com/dyingbleed/),且不得用于商业目的。
博客园博客已停止更新,博客地址:dyingbleed.com
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?