Reputation: 201
I'm trying to save a png image but I can't get the image to be created, despite this solution.
I'm using selenium webDriver to take a screenshot of the chrome browser window, the getScreenshotAs()
returns a byte array that I put into a ByteArrayInputStream
object. I also have a rectangle view
that contains the dimensions I want to crop the image to, using getSubimage()
.
with the code provided below, no image is created, when I add imgfile.createNewFile()
a file is created but is entirely empty and does not register as a 'png' file.
Essentially all I want to do is take an image that I have in memory as a byte array, crop it to specific dimensions, and save it as a png file. Really basic I know but I can't quite figure it out. Any help is greatly appreciated.
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);
Upvotes: 2
Views: 2824
Reputation: 417
I have tested your code sample and I am able to get a screenshot. Because I don't have a view
variable, just hardcoded some valid values as follows:
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;
You should add the assertion lines and figure out where the stream is being interrupted, but my guess would be that: 1) there is some problem with the view
variable and providing invalid values, 2) the output file imgfile
cannot be written (check for permissions, a correct path, etc)
Upvotes: 2