title: Robot screen capture - heap OutOfMemory while resizing
body: <p>I am using Robot's screenCapture method which returns BufferedImage, and then send using Socket to client on Android. If I don't reduce Quality then It works fine but it is very slow as Image is large and takes much time to send.
  I am trying to Reduce quality of BufferedImage(using ImageResizer Class), It works but for very limited time and then crash on server end.... It gives me following exception</p>
  
  <pre><code>Exception in thread "Thread-7" Exception in thread "Thread-8" java.lang.OutOfMemoryError: Java heap space
      at sun.awt.windows.WRobotPeer.getRGBPixels(WRobotPeer.java:64)
      at java.awt.Robot.createScreenCapture(Robot.java:444)
      at SystemController.screenCap(SystemController.java:71)
      at Server$ImageServer.run(Server.java:356)
      at java.lang.Thread.run(Thread.java:722)**
  </code></pre>
  
  <p>I am using following class for resizing</p>
  
  <pre><code>public class ImageResizer {
      public static ByteArrayOutputStream resizeImage(BufferedImage image) {
          ByteArrayOutputStream out = new ByteArrayOutputStream();
          try {
              float quality = 0.3f; // Change this as needed
              // get all image writers for JPG format
              Iterator&lt;ImageWriter&gt; writers = ImageIO
                      .getImageWritersByFormatName("jpg");
              if (!writers.hasNext()) {
                  throw new IllegalStateException("No writers found");
              }
              ImageWriter writer = writers.next();
              //ImageOutputStream ios = ImageIO.createImageOutputStream(os);
              try (ImageOutputStream ios = ImageIO.createImageOutputStream(out)) {
                  writer.setOutput(ios);
                  // set compression quality
                  ImageWriteParam param = writer.getDefaultWriteParam();
                  param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                  param.setCompressionQuality(quality);
                  writer.write(null, new IIOImage(image, null, null), param);
              }
          } catch (IOException ex) {
              ex.printStackTrace();
          }
          return out;
      }
  }
  </code></pre>
  
  <p>And this method is used for capturing</p>
  
  <pre><code>public ByteArrayOutputStream screenCap(Rectangle captureSize, int i) {
          robot = new Robot();
          screenImage = robot.createScreenCapture(captureSize);
          return ImageResizer.resizeImage(screenImage);
      }
  </code></pre>
  
  <p>What am I doing wrong?</p>