我有一个类似的字符串
String s = "123456789";
我想要一个带有从字符串生成的 QrCode 的 Vaadin 图像,以将其显示在窗口中。所以我想要这样的东西:
public Image toQr(String s) {
<...>
return imageOfQr;
}
add(toQr("Hello World"));
我该怎么做? 您能帮我提供具有相同输入和输出的完整方法吗?我对任何其他输出不感兴趣。
这是一个示例类,说明如何以两种不同的方式执行此操作。我还会检查 ZXingVaadin 插件,它可能会做类似的事情(我从未尝试过)。
package org.example.views;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.EAN13Writer;
import com.vaadin.flow.component.html.Image;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.AbstractStreamResource;
import com.vaadin.flow.server.StreamResource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@Route
public class BarcodeView extends VerticalLayout {
public BarcodeView() {
String barcodeText = "123456789012";
Image barcode = new Image();
barcode.setSrc(asStreamResource(generateEAN13BarcodeImage(barcodeText)));
add(barcode);
// Barcode images are typically small
// & no need for caching, using as data URL is fine as well
Image asDataUrl = new Image();
asDataUrl.setSrc(toDataUrl(generateEAN13BarcodeImage(barcodeText)));
add(asDataUrl);
}
private AbstractStreamResource asStreamResource(BufferedImage bufferedImage) {
return new StreamResource("barcode.png", (output, session) -> {
try {
ImageIO.write(bufferedImage, "png", output);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
public static final int BARCODE_W = 300;
public static final int BARCODE_H = 50;
public static BufferedImage generateEAN13BarcodeImage(String barcodeText) {
EAN13Writer barcodeWriter = new EAN13Writer();
BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.EAN_13, BARCODE_W, BARCODE_H);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
public String toDataUrl(BufferedImage image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(image, "png", baos);
return "data:image/png;base64," + jakarta.xml.bind.DatatypeConverter.printBase64Binary(baos.toByteArray());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}