/** This class contains two helper functions, for reading and writing images. */ import java.awt.*; import java.io.*; import java.awt.image.*; class ImageReaderWriter { /** Read an image from an InputStream. @param theComponent - images are device dependent so we need to have the component to generate the initial blank image. @param in - the input stream. @return the loaded image. */ static Image readImage(Component theComponent, ObjectInputStream in) throws IOException, ClassNotFoundException { int w = in.readInt(); int h = in.readInt(); int[] pixels = (int[])in.readObject(); Image img=theComponent.createImage(new MemoryImageSource(w,h,pixels,0,w)); // Now we need to wait until the image is fully produced // the MediaTracker constructor wants an ImageObserver // all components implement ImageObserver so use theComponent MediaTracker tracker = new MediaTracker(theComponent); // you can call addImage more times to track several images // with this one MediaTracker tracker.addImage(img, 0/*user selected id to identify the image*/); // you can also use waitForId(idNum) to wait for a specific image // this idNum is the same one passed in the addImage() call try { tracker.waitForAll(); } catch (InterruptedException e) {} return img; } /** Write an image to an OutputStream. @param img - the Image to be written. @param out - the output stream. */ static void writeImage(BufferedImage img, ObjectOutputStream out) throws IOException { int w = img.getWidth(null); int h = img.getHeight(null); int[] pixels = new int[w * h]; PixelGrabber pg = new PixelGrabber(img, 0, 0, w, h, pixels, 0, w); try { pg.grabPixels(); } catch (InterruptedException e) { System.err.println("interrupted waiting for pixels!"); return; } if ((pg.getStatus() & ImageObserver.ABORT) != 0) { System.err.println("image fetch aborted or errored"); return; } out.writeInt(w); out.writeInt(h); out.writeObject(pixels); } }