使用 Java 技术栈生成二维码

4 天前
 Honwhy

一般使用zxing 库就可以生成二维码了,但是要注意一个重要参数,ErrorCorrectionLevel 纠错能力等级,等级越高,内容码点越密集,纠错能力当然也越强(即使被遮挡了一部分也能还原)

<dependency>
  <groupId>com.google.zxing</groupId>
  <artifactId>core</artifactId>
  <version>3.5.2</version>
</dependency>
public enum ErrorCorrectionLevel {
    L(1),
    M(0),
    Q(3),
    H(2);
}

可以发现纠错等级越高,生成二维码的码点越密集。

左边 level=0 ,右边 level=3

| | |

如果为了生成更好一点的二维码,建议使用qrgen

<dependency>
  <groupId>com.github.aytchell</groupId>
  <artifactId>qrgen</artifactId>
  <version>3.0.0</version>
</dependency>

创建二维码

    private BufferedImage createRoundedQRCodeImage(String url, int width, int level) throws QrConfigurationException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, WriterException {
        QrCodeRenderer qrCodeRenderer = new QrCodeRenderer(PixelStyle.ROWS, MarkerStyle.ROUND_CORNERS);
        ColorConfig colorConfig = new ColorConfig(new RgbValue(0, 0, 0), new RgbValue(255, 255, 255));
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, getErrorCorrectionLevel(level));
        return qrCodeRenderer.encodeAndRender(url, colorConfig, width, width, hints);
    }

效果

--- 关于作者 ---

1590 次点击
所在节点    Java
4 条回复
geying
4 天前
支持开源
chunpuyin
4 天前
厉害呀。
Honwhy
4 天前
@geying
qrgen 地址:qrgen: https://github.com/honwhy/qrgen
我的 demo 项目地址:java-examples: https://github.com/honwhy/java-examples
公众号文章: https://mp.weixin.qq.com/s/yFy0P1j8naqXypn0xxlElw
totoro52
3 天前
二维码这种东西,不都是前端生成的吗

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1159004

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX