gpt4 book ai didi

java - java中如何保存图像文件?

转载 作者:行者123 更新时间:2023-12-01 11:40:14 25 4
gpt4 key购买 nike

我正在用java开发一个QR生成器应用程序。这是生成代码,

try {

ByteArrayOutputStream out = QRCode.from(txt_input.getText()).to(ImageType.PNG).stream();
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());

BufferedImage image = ImageIO.read(in);

lbl_output.setIcon(null);
lbl_output.setIcon(new ImageIcon(image));

String pic = "image";

} catch (Exception e) {
JOptionPane.showMessageDialog(null, " Please enter valid text !");
}

生成QR图像后,我需要保存它。所以我使用了这段代码,

JFileChooser save = new JFileChooser();
int response = save.showSaveDialog(null);

if (response == JFileChooser.APPROVE_OPTION) {
try {
File fileToSave = new File(pic + ".png");
ImageIO.write(image, "PNG", fileToSave);

} catch (Exception e) {

}
}

但是有一个异常(exception),例如,

java.lang.IllegalArgumentException: image == null!
at javax.imageio.ImageTypeSpecifier.createFromRenderedImage(ImageTypeSpecifier.java:925)
at javax.imageio.ImageIO.getWriter(ImageIO.java:1591)
at javax.imageio.ImageIO.write(ImageIO.java:1520)

最佳答案

这里没有理由使用ImageIO,因为您的QRCode类已经将PNG格式的图像写入字节数组。

相反,只需将字节复制到您想要的文件即可。

即:

ByteArrayOutputStream out = QRCode.from(txt_input.getText()).to(ImageType.PNG).stream();
byte[] bytes = out.toByteArray();

...

FileChooser save = new JFileChooser();
int response = save.showSaveDialog(null);

if (response == JFileChooser.APPROVE_OPTION) {
File fileToSave = new File(pic + ".png");

// Try-with-resource
try (OutputStream out = new FileOutputStream(fileToSave)) {
out.write(bytes);
out.flush();
}
}

关于java - java中如何保存图像文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29588433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com