关于Java:如何将BufferedImage对象保存到文件?

How to save BufferedImage object to file?

尽管有此解决方案,我仍试图保存png图像,但无法创建该图像。

我正在使用selenium webDriver拍摄chrome浏览器窗口的屏幕截图,getScreenshotAs()返回一个字节数组,我将其放入了ByteArrayInputStream对象中。我还有一个矩形view,其中包含要使用getSubimage()裁剪图像的尺寸。

使用下面提供的代码,当我添加imgfile.createNewFile()时,不会创建图像,但是会创建一个文件,但文件完全为空,不会注册为" png"文件。

基本上,我要做的只是将内存中的图像作为字节数组,将其裁剪为特定的尺寸,然后将其保存为png文件。我真的很基础,但我不太清楚。非常感谢您的帮助。

1
2
3
4
5
6
7
8
ByteArrayInputStream imgbytes = new ByteArrayInputStream(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES));
BufferedImage bimg = ImageIO.read(imgbytes);

bimg = bimg.getSubimage(view.getX(), view.getY(), view.getWidth(), view.getWidth());

File imgfile = new File("C:\\\\Users\\\\User\\\\Documents\\\
ewimg.png"
);
ImageIO.write(bimg,"png", imgfile);


我已经测试了您的代码示例,并且可以获取屏幕截图。因为我没有view变量,所以将一些有效值硬编码如下:

1
2
3
4
5
6
7
8
9
ByteArrayInputStream imgbytes = new ByteArrayInputStream(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES));
assert imgbytes.available() > 0;
BufferedImage bimg = ImageIO.read(imgbytes);
bimg = bimg.getSubimage(0, 0, 500, 500);
assert bimg.getHeight() > 0;
assert bimg.getWidth() > 0;
File imgfile = new File("screenshot.png");
ImageIO.write(bimg,"png", imgfile);
assert imgfile.length() > 0;

您应该添加断言行并找出流在何处中断,但是我的猜测是:1)view变量存在一些问题,并提供了无效的值,2)输出文件无法写入(检查权限,正确的路径等)