【发布时间】:2022-01-18 13:32:45
【问题描述】:
我正在尝试修改以下方法,使其返回byte[](字节数组)而不是BufferedImage。我还可以使用另一个返回 byte[] 的实现,但该实现不可配置,如下所示。那么,我怎样才能让这个方法返回byte[] 而不是BufferedImage?
public static BufferedImage getQRCode(String targetUrl, int width,
int height) {
Hashtable<EncodeHintType, Object> hintMap = new Hashtable<>();
hintMap.put(EncodeHintType.ERROR_CORRECTION,
ErrorCorrectionLevel.L);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix byteMatrix = qrCodeWriter.encode(targetUrl,
BarcodeFormat.QR_CODE, width, height, hintMap);
int CrunchifyWidth = byteMatrix.getWidth();
BufferedImage image = new BufferedImage(CrunchifyWidth,
CrunchifyWidth, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, CrunchifyWidth, CrunchifyWidth);
graphics.setColor(Color.BLACK);
for (int i = 0; i < CrunchifyWidth; i++) {
for (int j = 0; j < CrunchifyWidth; j++) {
if (byteMatrix.get(i, j)) {
graphics.fillRect(i, j, 1, 1);
}
}
}
return image;
}
【问题讨论】:
-
你的 byte[] 应该是什么?您可以使用 ImageIO 并将 png 写入字节 []?您可以获取缓冲图像的栅格数据吗?
-
@matt 感谢您的帮助。我正在尝试使用 ZXing 生成 QR 码,当我使用返回
byte[]的方法时,我可以获得图像作为响应。但是当我使用BufferedImage时,我得到 "No converter for [class java.awt.image.BufferedImage] with preset Content-Type 'null'" 错误。出于这个原因,我想将返回类型转换为byte[]以轻松解决问题。 -
好的,那么提供的答案可能就是您想要的。您想创建一个完整的图像并将其作为字节返回。
标签: java arrays spring file qr-code