title: Preventing BufferedImage To Throw OutOfMemoryError
body: <p>Is it possible prevent BufferedImage to throw OutOfMemoryError exceptions by creating byte by byte a BufferedImage?</p>
  
  <p>I am using this method to crop images: </p>
  
  <pre><code>public static void cropImage(File originalImage, File to, int x1, int y1, int x2, int y2) {
      try {
          BufferedImage source = ImageIO.read(originalImage);
  
          String mimeType = "image/jpeg";
          if (to.getName().endsWith(".png")) {
              mimeType = "image/png";
          }
          if (to.getName().endsWith(".gif")) {
              mimeType = "image/gif";
          }
          int width = x2 - x1;
          int height = y2 - y1;
  
          // out
          BufferedImage dest = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
          Image croppedImage = source.getSubimage(x1, y1, width, height);
          Graphics graphics = dest.getGraphics();
          graphics.setColor(Color.WHITE);
          graphics.fillRect(0, 0, width, height);
          graphics.drawImage(croppedImage, 0, 0, null);
          ImageWriter writer = ImageIO.getImageWritersByMIMEType(mimeType).next();
          ImageWriteParam params = writer.getDefaultWriteParam();
          writer.setOutput(new FileImageOutputStream(to));
          IIOImage image = new IIOImage(dest, null, null);
          writer.write(null, image, params);
          writer.dispose();
          source = null;
      } catch (Exception e) {
          throw new RuntimeException(e);
      }
  
  }
  </code></pre>
  
  <p>I have a MaxPermSize of 512m and if someone upload a 16000x10000 image I will get an OutOfMemoryError on: <code>BufferedImage source = ImageIO.read(originalImage);</code></p>