Honwhy
V2EX  ›  Java

使用 Java 技术栈生成二维码

  •  
  •   Honwhy ·
    honwhy · Sep 13, 2025 · 9257 views
    This topic created in 278 days ago, the information mentioned may be changed or developed.

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

    效果

    --- 关于作者 ---

    5 replies    2026-01-31 09:08:08 +08:00
    geying
        1
    geying  
       Sep 14, 2025
    支持开源
    chunpuyin
        2
    chunpuyin  
       Sep 14, 2025
    厉害呀。
    Honwhy
        3
    Honwhy  
    OP
       Sep 14, 2025
    @geying
    qrgen 地址:qrgen: https://github.com/honwhy/qrgen
    我的 demo 项目地址:java-examples: https://github.com/honwhy/java-examples
    公众号文章: https://mp.weixin.qq.com/s/yFy0P1j8naqXypn0xxlElw
    MIUIOS
        4
    MIUIOS  
       Sep 15, 2025
    二维码这种东西,不都是前端生成的吗
    Honwhy
        5
    Honwhy  
    OP
       Jan 31
    @MIUIOS 我们的业务场景决定了,在底图图片右下角贴二维码的行为,最合适的处理地方是在后端。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1502 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 16:31 · PVG 00:31 · LAX 09:31 · JFK 12:31
    ♥ Do have faith in what you're doing.