我们可以通过以下方式创建FX Image对象:
byte [] bytes = ------; //valid image in bytes
javafx.scene.image.Image image = new Image(new ByteArrayInputStream(bytes));
同样的方式也可以应用到 ImageView 上。
我需要相反的操作,不需要先将其转换为 BufferedImage (SwingFXUtils.fromFXImage(image,null))。
这样我就能直接将字节写入文件。
我尝试过以下方法:
PixelReader pixelReader = image.getPixelReader();
int width = (int)image.getWidth();
int height = (int)image.getHeight();
byte[] buffer = new byte[width * height * 4];
pixelReader.getPixels(
0,
0,
width,
height,
PixelFormat.getByteBgraInstance(),
buffer,
0,
width * 4
);
然而,通过写入byte []缓冲区生成的文件不是有效的图像。
对此有何见解?
编辑:在如何从javafx ImageView获取byte []中给出的解决方案不能应用于我的问题。正如我已经清楚地提到的那样,我不想使用SwingFXUtils将其转换为BufferedImage。 此外,我想将其转换为字节数组,以便将其写入图像文件。