如何将 BufferedImage 对象保存到文件?
How to save BufferedImage object to file?
我正在尝试保存 png 图像,但我无法创建图像,尽管 this solution。
我正在使用 selenium webDriver 截取 chrome 浏览器 window 的屏幕截图,getScreenshotAs()
returns 我放入 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);
我已经测试了您的代码示例,并且可以获取屏幕截图。因为我没有 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
(检查权限、正确的路径等)
我正在尝试保存 png 图像,但我无法创建图像,尽管 this solution。
我正在使用 selenium webDriver 截取 chrome 浏览器 window 的屏幕截图,getScreenshotAs()
returns 我放入 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);
我已经测试了您的代码示例,并且可以获取屏幕截图。因为我没有 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
(检查权限、正确的路径等)