title: How to save BufferedImage object to file?
body: <p>I'm trying to save a png image but I can't get the image to be created, despite <a href="https://stackoverflow.com/questions/12674064/how-to-save-a-bufferedimage-as-a-file">this solution</a>.</p>
  
  <p>I'm using selenium webDriver to take a screenshot of the chrome browser window, the <code>getScreenshotAs()</code> returns a byte array that I put into a <code>ByteArrayInputStream</code> object. I also have a rectangle <code>view</code> that contains the dimensions I want to crop the image to, using <code>getSubimage()</code>.</p>
  
  <p>with the code provided below, no image is created, when I add <code>imgfile.createNewFile()</code> a file is created but is entirely empty and does not register as a 'png' file.</p>
  
  <p>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.</p>
  
  <pre class="lang-java prettyprint-override"><code>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);
  </code></pre>