code: public static void write (BufferedImage image, OutputStream out)
          throws IOException
      {
          DataOutputStream dout = new DataOutputStream(out);
  
          // write the image dimensions
          int width = image.getWidth(), height = image.getHeight();
          dout.writeInt(width);
          dout.writeInt(height);
  
          // write the color model information
          IndexColorModel cmodel = (IndexColorModel)image.getColorModel();
          int tpixel = cmodel.getTransparentPixel();
          dout.writeInt(tpixel);
          int msize = cmodel.getMapSize();
          int[] map = new int[msize];
          cmodel.getRGBs(map);
          dout.writeInt(msize);
          for (int element : map) {
              dout.writeInt(element);
          }
  
          // write the raster data
          DataBufferByte dbuf = (DataBufferByte)image.getRaster().getDataBuffer();
          byte[] data = dbuf.getData();
          if (data.length != width * height) {
              String errmsg = "Raster data not same size as image! [" +
                  width + "x" + height + " != " + data.length + "]";
              throw new IllegalStateException(errmsg);
          }
          dout.write(data);
          dout.flush();
      }
docs: Writes the supplied image to the supplied output stream.
  
  @exception IOException thrown if an error occurs writing to the output stream.