使用以下库:
qrgen-1.2,zxing-core-1.7和
zxing-j2se-1.7我生成了QRCode:

    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类的实例?如我所见,该库没有为用户提供可以执行此操作的方法,所以有可能吗?可以将流转换为图像吗?

最佳答案

只需将qr代码写入字节数组输出流,然后在流中使用字节数组创建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;
}

09-30 14:30
查看更多