title: Sending an image as a byte array between client and server
body: <p>I can successfully send and draw a resized, 125 x 125 image from my client to my server. only problem is, thats way too small. I want to be able to send a larger image but the byte array can't handle it and I get a java heap exception. currently I'm using this to interpret my image. Is there a more efficient way?</p>
  
  <p>On the client</p>
  
  <pre><code>screenShot = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
                  screenShot = resize(screenShot, 125, 125);
  
                  ByteArrayOutputStream byteArrayO = new ByteArrayOutputStream();
                  ImageIO.write(screenShot,"PNG",byteArrayO);
                  byte [] byteArray = byteArrayO.toByteArray();
                  out.writeLong(byteArray.length);
                  out.write(byteArray);
  </code></pre>
  
  <p>resize method as called above.</p>
  
  <pre><code>    public static BufferedImage resize(BufferedImage img, int newW, int newH) {  
      int w = img.getWidth();  
      int h = img.getHeight();  
      BufferedImage dimg = new BufferedImage(newW, newH, img.getType()); 
      Graphics2D g = dimg.createGraphics();  
      g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
      RenderingHints.VALUE_INTERPOLATION_BILINEAR);  
      g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);  
      g.dispose();  
      return dimg;  
     } 
  </code></pre>
  
  <p>server that interprets the image</p>
  
  <pre><code>in = new DataInputStream(Client.getInputStream());
              long nbrToRead = in.readLong();
              byte[] byteArray = new byte[(int) nbrToRead];
              int nbrRd = 0;
              int nbrLeftToRead = (int) nbrToRead;
  
              while (nbrLeftToRead &gt; 0) {
                  int rd = in.read(byteArray, nbrRd, nbrLeftToRead);
                  if (rd &lt; 0)
                      break;
                  nbrRd += rd; // accumulate bytes read
                  nbrLeftToRead -= rd;
              }
              ByteArrayInputStream byteArrayI = new ByteArrayInputStream(
                      byteArray);
              image = ImageIO.read(byteArrayI);
  
              if (image != null) {
                  paint(f.getGraphics(), image);
              } else {
                  System.out.println("null image.");
              }
  </code></pre>
  
  <p>as you can tell the code is massive and most likely inefficient. I could send 1/10 of the image 10 times for with and height, drawing on those parts instead but I wanted to know if there was an easier way to do this. </p>