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