如何将BufferedImage对象保存到文件?

时间:2019-05-23 00:11:28

标签: java file-io bufferedimage

我正在尝试保存png图像,尽管有this solution,但我无法创建该图像。

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

使用下面提供的代码,当我添加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\\newimg.png"); ImageIO.write(bimg, "png", imgfile); 时,将不会创建任何图像,但是文件完全为空且不会注册为“ png”文件。

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

from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
import random

1 个答案:

答案 0 :(得分:2)

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

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)输出文件imgfile无法写入(检查权限,正确的路径等)