【问题标题】:Convert QRCode to Image. Java将二维码转换为图像。爪哇
【发布时间】:2015-10-23 22:11:31
【问题描述】:

使用以下库: qrgen-1.2、zxing-core-1.7 和 zxing-j2se-1.7 我生成了二维码:

    ByteArrayOutputStream out = QRCode.from(output.toString()).withSize(1000,1000).to(ImageType.PNG).stream();
    FileOutputStream fout = new FileOutputStream(new File("D:\\QR_Code.JPG"));
    fout.write(out.toByteArray());
    fout.flush();
    fout.close();

我打算用它做的是将代码发送到接受 java.awt.Image 的方法。 如何在不首先创建 QRCode.JPG 的情况下将 QRCode 类的实例转换为 Image 类的实例?正如我所看到的,这个库没有为用户提供可以执行此操作的方法,所以有可能吗?我可以将流转换为图像吗?

【问题讨论】:

  • 我不知道那些库,但是试试这个:BufferedImage image = ImageIO.read(new ByteArrayInputStream(out.toByteArray()));BufferedImageImage 的子类,假设你在谈论java.awt.image.Image
  • 输入错误并且由于某种原因无法编辑 - 应该是 java.awt.Image,而不是 java.awt.image.Image

标签: java image


【解决方案1】:

只需将二维码写入字节数组输出流,然后在流中使用字节数组创建BufferedImage

import net.glxn.qrgen.QRCode;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public static BufferedImage generate() {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        QRCode.from("http://www.stackoverflow.com").writeTo(baos);
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        return ImageIO.read(bais);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    • 2022-01-21
    相关资源
    最近更新 更多