// This example is from the book _Java AWT Reference_ by John Zukowski. // Written by John Zukowski. Copyright (c) 1997 O'Reilly & Associates. // You may study, use, modify, and distribute this example for any purpose. // This example is provided WITHOUT WARRANTY either expressed or implied. import java.awt.*; import java.awt.image.*; import java.util.*; import java.io.*; public class PPMImageDecoder implements ImageProducer { /* Since done in-memory, only one consumer */ private ImageConsumer consumer; boolean loadError = false; int width; int height; int store[][]; Hashtable props = new Hashtable(); /* Format of Ppm file is single pass/frame, w/ complete scan lines in order */ private static int PpmHints = (ImageConsumer.TOPDOWNLEFTRIGHT | ImageConsumer.COMPLETESCANLINES | ImageConsumer.SINGLEPASS | ImageConsumer.SINGLEFRAME); /* There is only a single consumer. When it registers, produce image. */ /* On error, notify consumer */ public synchronized void addConsumer (ImageConsumer ic) { consumer = ic; try { produce(); } catch (Exception e) { if (consumer != null) consumer.imageComplete (ImageConsumer.IMAGEERROR); } consumer = null; } /* If consumer passed to routine is single consumer, return true, else false */ public synchronized boolean isConsumer (ImageConsumer ic) { return (ic == consumer); } /* Disables consumer if currently consuming */ public synchronized void removeConsumer (ImageConsumer ic) { if (consumer == ic) consumer = null; } /* Production is done by adding conumer */ public void startProduction (ImageConsumer ic) { addConsumer (ic); } public void requestTopDownLeftRightResend (ImageConsumer ic) { // Not needed. The data is always in this format. } /* Production Process: Prerequisite: Image already read into store array. (readImage) props / width / height already set (readImage) Assumes RGB Color Model - would need to filter to change. Sends Ppm Image data to consumer. Pixels sent one row at a time. */ private void produce () { ColorModel cm = ColorModel.getRGBdefault(); if (consumer != null) { if (loadError) { consumer.imageComplete (ImageConsumer.IMAGEERROR); } else { consumer.setDimensions (width, height); consumer.setProperties (props); consumer.setColorModel (cm); consumer.setHints (PpmHints); for (int j=0;j 255)) { throw (new AWTException ("Invalid Colors " + maxColors)); } store = new int[height][width]; if (raw) { byte row[] = new byte [width*3]; for (int i=0;i-->