2

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);
Tim51092
  • 201
  • 1
  • 6
  • You are sure that 'new ByteArrayInputStream(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES));' is provding you with some data? You might want to post that code as well. – second May 23 '19 at 00:25
  • Not sure the issue is with the "saving" of the image, it's more likely with the generation, but it's impossible to know based on the out of context code – MadProgrammer May 23 '19 at 00:26
  • @MadProgrammer I apologize for the lack of context, I have edited the question to provide some more details. Please let me know if there's anything else I can add that will help. – Tim51092 May 23 '19 at 00:47
  • `ImageIO.write(...)` returns a `boolean` indicating whether the image was written or not. What is the value in your case? – Harald K May 23 '19 at 07:19

1 Answers1

2

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)

Heraldo
  • 407
  • 2
  • 11