将 javafx.scene.image.Image 写入文件? [英] Writing javafx.scene.image.Image to file?
问题描述
我将如何将 javafx.scene.image.Image 图像写入文件.我知道您可以在 BufferedImages 上使用 ImageIO,但是有什么办法可以用 javafx Image 做到这一点吗?
How would I go about writing a javafx.scene.image.Image image to a file. I know you can use ImageIO on BufferedImages but is there any way to do it with a javafx Image?
推荐答案
将近 3 年后,我现在有知识来做和回答这个问题.是的,原始答案也是有效的,但它涉及首先将图像转换为 BufferedImage 并且我理想地希望完全避免摆动.虽然这确实输出了图像的原始 RGBA 版本,但足以满足我的需要.我实际上可以只使用原始 BGRA,因为我正在编写软件来打开结果,但由于 gimp 无法打开,我想我会将其转换为 RGBA.
Almost 3 years later and I now have the knowledge to do and answer this. Yes the original answer was also valid but it involved first converting the image to a BufferedImage and I ideally wanted to avoid swing entirely. While this does output the raw RGBA version of the image that's good enough for what I needed to do. I actually could just use raw BGRA since I was writing the software to open the result but since gimp can't open that I figure I'd convert it to RGBA.
Image img = new Image("file:test.png");
int width = (int) img.getWidth();
int height = (int) img.getHeight();
PixelReader reader = img.getPixelReader();
byte[] buffer = new byte[width * height * 4];
WritablePixelFormat<ByteBuffer> format = PixelFormat.getByteBgraInstance();
reader.getPixels(0, 0, width, height, format, buffer, 0, width * 4);
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("test.data"));
for(int count = 0; count < buffer.length; count += 4) {
out.write(buffer[count + 2]);
out.write(buffer[count + 1]);
out.write(buffer[count]);
out.write(buffer[count + 3]);
}
out.flush();
out.close();
} catch(IOException e) {
e.printStackTrace();
}
这篇关于将 javafx.scene.image.Image 写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!