【问题标题】:How to save BufferedImage object to file?如何将 BufferedImage 对象保存到文件中?
【发布时间】:2019-05-23 00:11:27
【问题描述】:

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

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

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

基本上,我要做的就是将内存中的图像作为字节数组,将其裁剪为特定尺寸,然后将其保存为 png 文件。我知道真的很基本,但我无法弄清楚。非常感谢任何帮助。

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);

【问题讨论】:

  • 你确定'new ByteArrayInputStream(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES));'正在向您提供一些数据吗?您可能也想发布该代码。
  • 不确定问题出在图像的“保存”上,更可能是生成问题,但根据上下文代码无法知道
  • @MadProgrammer 对于缺少上下文,我深表歉意,我已编辑问题以提供更多详细信息。请让我知道是否还有其他可以帮助的内容。
  • ImageIO.write(...) 返回一个boolean 指示图像是否已写入。你的情况有什么价值?

标签: java file-io bufferedimage


【解决方案1】:

我已经测试了您的代码示例,并且可以获取屏幕截图。因为我没有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)输出文件@987654324 @ 无法写入(检查权限、正确的路径等)

【讨论】:

    猜你喜欢
    • 2011-10-07
    • 2012-09-22
    • 2011-05-17
    • 2011-01-26
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多