我拍了一张屏幕快照,然后尝试获取图像的一部分,当我尝试将它保存到文件时,它不起作用。 很乐意得到任何建议
Rectangle Rect = new Rectangle(10, 10, 50, 50);
File file = new File("D:\\output.png");
RenderedImage renderedImage = SwingFXUtils.fromFXImage(browser.snapshot(null, null), null);
try {
ImageIO.write((RenderedImage) renderedImage.getData(Rect),"png",file);
} catch (IOException ex { Logger.getLogger(JavaFXApplication3.class.getName()).log(Level.SEVERE, null, ex);
}
所以我终于得到了并且它起作用了
File file = new File("D:\\output.png");
BufferedImage image = SwingFXUtils.fromFXImage(browser.snapshot(null, null), null);
try {
ImageIO.write(image.getSubimage(100, 100, 50, 50) , "png", file);
} catch (IOException ex) {
Logger.getLogger(JavaFXApplication3.class.getName()).log(Level.SEVERE, null, ex);
}
最佳答案
我的猜测是您无法将从 .getData()
方法中检索到的 Raster
转换为图像。虽然技术上应该可以获取光栅,将其转换为 WritableRaster
并将其包装在 RenderedImage
中,但我建议您基本上复制图像的一部分.
快速SSCE :
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.*;
import java.io.File;
public class Test {
public static void main(String[] args) throws Exception {
BufferedImage original = new BufferedImage(100, 100, BufferedImage.TYPE_3BYTE_BGR);
// Crop away 10 pixels pixels and only copy 40 * 40 (the width and height of the copy-image)
BufferedImage copy = original.getSubimage(10, 10, 50, 50);
ImageIO.write(copy, "png", new File("Test.png"));
}
}
这对我有用,所以如果您遇到更多麻烦,您可能会考虑确保正确获取输入。如果您的问题是程序“卡住了”,请先使用虚拟图像尝试上面的代码。
希望对您有所帮助:-)
编辑:我不知道有一个名为 getSubimage 的方法,所以我用该方法替换了上面的代码。感谢安德鲁·汤普森。
关于java - 如何将光栅转换为渲染图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16094401/