You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vaadin中将字符串转换为二维码图片?

实现Vaadin二维码Image组件

首先需要引入二维码生成依赖,以Maven为例,添加ZXing的相关依赖到pom.xml:

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.5.3</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.5.3</version>
</dependency>

接下来实现要求的toQr方法,生成Vaadin的Image组件:

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.vaadin.flow.component.html.Image;
import com.vaadin.flow.server.StreamResource;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public Image toQr(String s) {
    QRCodeWriter qrCodeWriter = new QRCodeWriter();
    try {
        // 生成二维码矩阵,设置尺寸为200x200
        BitMatrix bitMatrix = qrCodeWriter.encode(s, BarcodeFormat.QR_CODE, 200, 200);
        
        // 将矩阵转为PNG字节流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);
        
        // 创建Vaadin的StreamResource,用于加载二维码图片
        StreamResource resource = new StreamResource("qrcode.png", 
            () -> new ByteArrayInputStream(outputStream.toByteArray()));
        
        // 返回Image组件
        return new Image(resource, "QR Code for: " + s);
    } catch (WriterException | IOException e) {
        throw new RuntimeException("Failed to generate QR code", e);
    }
}

使用方式和你要求的一致:

add(toQr("123456789"));

内容的提问来源于stack exchange,提问作者Ji Lin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 03:33:15