V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Honwhy
V2EX  ›  Java

使用 Java 技术栈生成二维码

  •  
  •   Honwhy ·
    honwhy · 17 小时 5 分钟前 · 609 次点击

    一般使用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);
        }
    

    效果

    --- 关于作者 ---

    3 条回复    2025-09-14 10:25:25 +08:00
    geying
        1
    geying  
       2 小时 37 分钟前
    支持开源
    chunpuyin
        2
    chunpuyin  
       2 小时 27 分钟前
    厉害呀。
    Honwhy
        3
    Honwhy  
    OP
       1 小时 17 分钟前
    @geying
    qrgen 地址:qrgen: https://github.com/honwhy/qrgen
    我的 demo 项目地址:java-examples: https://github.com/honwhy/java-examples
    公众号文章: https://mp.weixin.qq.com/s/yFy0P1j8naqXypn0xxlElw
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2660 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 18ms · UTC 03:42 · PVG 11:42 · LAX 20:42 · JFK 23:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.