Home > Articles > Programming > Java

  • Print
  • + Share This
Like this article? We recommend

PCX Reader Plug-in’s Architecture

This section explores the architecture of the PCX reader plug-in. This architecture is based on two classes: a service provider interface and an image reader. Although many reader plug-ins also include a pair of classes that handle metadata (data describing other data—the name of an image’s author, for example), PCX is rather limited in terms of metadata, so I chose to ignore metadata classes.

Service Provider Interface

The PCX reader plug-in’s PCXImageReaderSpi class subclasses the abstract javax.imageio.spi.ImageReaderSpi class and describes the plug-in’s service provider interface (SPI). The SPI provides plug-in information to Image I/O (via a constructor call to its superclass), lets Image I/O know if the input source’s content can be decoded, creates an instance of the image reader, and more:

public class PCXImageReaderSpi extends ImageReaderSpi
{
  public PCXImageReaderSpi ()
  {
   super ("JavaJeff",     // vendorName
       "1.0",        // version
       new String [] { "PCX" }, // names
       new String [] { "pcx" }, // suffixes
       new String [] { "image/x-pcx" }, // MIMETypes
       "ca.mb.javajeff.pcx.PCXImageReader", // readerClassName
       STANDARD_INPUT_TYPE, // inputTypes
       null,        // writerSpiNames
       false,        // supportsStandardStreamMetadataFormat
       null,        // nativeStreamMetadataFormatName
       null,        // nativeStreamMetadataFormatClassName
       null,        // extraStreamMetadataFormatNames
       null,        // extraStreamMetadataFormatClassNames
       false,        // supportsStandardImageMetadataFormat
       null,        // nativeImageMetadataFormatName
       null,        // nativeImageMetadataFormatClassName
       null,        // extraImageMetadataFormatNames
       null);        // extraImageMetadataFormatClassNames
  }

  // Additional methods.
}

The code fragment above, excerpted from the plug-in’s PCXImageReaderSpi.java source file (see this article’s archive in the Resources section for this and other files), declares the PCXImageReaderSpi class with a constructor that invokes the ImageReaderSpi constructor with plug-in–specific information:

  • vendor name: a String that identifies the plug-in’s vendor. This string is returned by the inherited public String getVendorName() method.
  • version: a String that identifies the plug-in version number. This string is returned by the inherited public String getVersion() method.
  • names: a non-null array of Strings that identify human-readable names for the formats understood by the plug-in. For example, an image reader might process PBM (portable bitmap) and PNM (portable anymap) files: PBM and PNM are the human-readable names. At least one entry is mandatory. This array is returned by the inherited public String[] getFormatNames() method.
  • suffixes: an array of Strings that identify file suffixes associated with the formats understood by the plug-in—pbm and pnm (two formats), or jpg and jpeg (one format) are examples. This array, which may be null if no suffixes associate with the formats, is returned by the inherited public String[] getFileSuffixes() method.
  • MIME types: an array of Strings that identify Multipurpose Internet Mail Extensions (MIME) types associated with the formats understood by the plug-in (the unofficial image/x-png and official image/png MIME types are examples). This array, which may be null if no MIME types are associated with the formats, is returned by the inherited public String[] getMIMETypes() method.
  • reader classname: a non-null String that specifies the fully qualified name of the associated image reader. This string is returned by the inherited public String getPluginClassName() method.
  • input types: a non-null array of Classes that specify the legal types of objects that may be used as arguments to the associated image reader’s setInput() method. This array is returned by the public Class[] getInputTypes() method.
  • writer SPI names: an array of Strings that specify the fully qualified names of all the javax.imageio.ImageWriterSpis that understand the internal metadata representation used by the image reader associated with this SPI. This array, which may be null, is returned by the public String[] getImageWriterSpiNames() method.
  • supports standard stream metadata format indicator: a Boolean value that indicates whether a stream metadata (metadata that applies to all images) object can use trees described by the standard metadata format. This value is returned by the inherited public boolean isStandardStreamMetadataFormatSupported() method.
  • native stream metadata format name: a String that identifies the "native" stream metadata format for this plug-in, which typically allows for lossless encoding and transmission of the stream metadata stored in the format handled by this plug-in. This string, which may be null, is returned by the inherited public String getNativeStreamMetadataFormatName() method.
  • native stream metadata format classname: a String, which may be null, which is used to instantiate a metadata format object. This object is returned by a public IIOMetadataFormat getNativeStreamMetadataFormat(String formatName) method that the plug-in must supply.
  • extra stream metadata format names: an array of Strings that specify the names of additional document formats, other than the native and standard formats, recognized by the getAsTree() and setFromTree() methods on the stream metadata objects produced or consumed by this plug-in. This array, which may be null, is returned by the inherited public String[] getExtraStreamMetadataFormatNames() method.
  • extra stream metadata format classnames: an array of Strings that are used to instantiate a metadata format object. This object is returned by the inherited public IIOMetadataFormat getStreamMetadataFormat(String formatName) method. The array may be null.
  • supports standard image metadata format indicator: a Boolean value that indicates whether an image metadata (metadata that applies to a specific image) object can use trees described by the standard metadata format. This value is returned by the inherited public boolean isStandardImageMetadataFormatSupported() method.
  • native image metadata format name: a String that identifies the "native" image metadata format for this plug-in, which typically allows for lossless encoding and transmission of the image metadata stored in the format handled by this plug-in. This string, which may be null, is returned by the inherited public String getNativeStreamMetadataFormatName() method.
  • native image metadata format classname: a String, which may be null, which is used to instantiate a metadata format object. This object is returned by a public IIOMetadataFormat getNativeImageMetadataFormat(String formatName) method that the plug-in must supply.
  • extra image metadata format names: an array of Strings that specify the names of additional document formats, other than the native and standard formats, recognized by the getAsTree() and setFromTree() methods on the image metadata objects produced or consumed by this plug-in. This array, which may be null, is returned by the inherited public String[] getExtraImageMetadataFormatNames() method.
  • extra image metadata format classnames: an array of Strings that are used to instantiate a metadata format object. This object is returned by the inherited public IIOMetadataFormat getImageMetadataFormat(String formatName) method. The array may be null.

In addition to providing a constructor that passes the previously listed information to its superclass, PCXImageReaderSpi implements three abstract methods that it inherits from its superclass. These methods tell Image I/O if the associated image reader can process the contents of an input source, create an image reader, and specify a localized description of the plug-in:

  • public abstract boolean canDecodeInput(Object source) returns true if the source object appears to describe a format that is recognized by this SPI’s associated image reader. This check does not guarantee that reading will succeed; only that there appears to be a chance for success based on a brief inspection of the source’s content. The state of this object must not be changed so that other SPIs can properly determine if their image readers can decode the source’s content (in the event that this SPI’s image reader is unable to do so):
    public boolean canDecodeInput (Object input) throws IOException
    {
      // The input source must be an ImageInputStream because the constructor
      // passes STANDARD_INPUT_TYPE (an array consisting of ImageInputStream)
      // as the only type of input source that it will deal with to its
      // superclass.
    
      if (!(input instanceof ImageInputStream))
        return false;
    
      ImageInputStream stream = (ImageInputStream) input;
    
      // Read and validate the input source’s header.
    
      byte [] header = new byte [128];
      try
      {
        // The input source’s current position must be preserved so that
        // other ImageReaderSpis can determine if they can decode the input
        // source’s format, should this input source be unable to handle the 
        // decoding. Because the input source is an ImageInputStream, its
        // mark() and reset() methods are called to preserve the current
        // position.
    
        stream.mark ();
        stream.readFully (header);
        stream.reset ();
      }
      catch (IOException e)
      {
        return false;
      }
    
      // Verify Manufacturer field.
    
      if (header [0] != 10)
        return false;
    
      // Verify Version field.
    
      if (header [1] != 5)
        return false;
    
      // Verify Encoding field.
    
      if (header [2] != 1)
        return false;
    
      // Verify BitsPerPixel field.
    
      if (header [3] != 1 && header [3] != 4 && header [3] != 8)
        return false;
    
      // Verify NPlanes field.
    
      if (header [65] != 1 && header [65] != 3)
        return false;
    
      // Verify BitsPerPixel with NPlanes.
    
      if ((header [3] == 1 || header [3] == 4) && header [65] == 3)
        return false;
    
      // Verify BytesPerLine field.
    
      if ((header [66] & 1) == 1) // Does field’s least-significant byte odd?
        return false;
    
      // Input source points to a valid PCX file, in so far as the header is
      // concerned.
    
      return true;
    }
  • public abstract ImageReader createReaderInstance(Object extension) returns an instance of the image reader associated with this SPI. The returned image reader is in an initial state as if its public void reset() method had been called. By default, extension contains a null reference. However, an ImageReaderSpi subclass could override the public ImageReader createReaderInstance() method (which invokes createReaderInstance (null)) to create some sort of plug-in-specific object, and pass this object to createReaderInstance(Object extension):
    public ImageReader createReaderInstance (Object extension)
      throws IOException
    {
      // Inform the PCX image reader that this PCX image reader SPI is the
      // originating provider -- the object that creates the PCX image reader.
    
      return new PCXImageReader (this);
    }
  • public abstract String getDescription(Locale locale) returns a brief, human-readable description of this SPI and its associated image reader. If possible, the resulting string should be localized for the supplied locale. This method is inherited from the javax.imageio.spi.IIOServiceProvider ancestor class:
    public String getDescription (java.util.Locale locale)
    {
      // This method should return a localized description.
    
      return "PCX Reader Plug-in by Jeff Friesen";
    }

Image Reader

The PCX reader plug-in’s PCXImageReader class subclasses the abstract javax.imageio.ImageReader class and functions as the plug-in’s image reader. The PCX SPI creates an image reader by invoking an image reader constructor that takes an SPI instance as its argument. The constructor forwards this instance to its superclass:

public class PCXImageReader extends ImageReader
{
  // image width (in pixels) -- returned from getWidth()

  private int width;

  // image height (in pixels) -- returned from getHeight()

  private int height;

  // image bits per pixel -- must be 1, 4, or 8

  private int bitsPerPixel;

  // image planes -- must be 1 or 3

  private int nPlanes;

  // number of bytes per line per plane -- must be an even number

  private int bytesPerLine;

  // bytesPerLine * nPlanes

  private int scanlineLength;

  // storage location for each read scanline

  private byte [] scanline;

  // merged EGA and VGA palettes

  private byte [] palette = new byte [256*3];

  // input source as an ImageInputStream

  private ImageInputStream stream;

  // flag to prevent the same header from being read multiple times

  private boolean gotHeader;

  public PCXImageReader (ImageReaderSpi originatingProvider)
  {
   // Save the identity of the ImageReaderSpi subclass that invoked this
   // constructor.

   super (originatingProvider);
  }

  // Additional methods.
}

The code fragment above, excerpted from the plug-in’s PCXImageReader.java source file, declares the PCXImageReader class with a constructor that saves the identity of the SPI that created the image reader and several fields that are accessed by seven abstract methods that PCXImageReader must implement:

  • public abstract int getHeight(int imageIndex) returns the height of an image from the input source. Some formats, such as GIF 89a, can store multiple images. In these cases, the image whose height is to be returned is identified by the zero-based imageIndex. If there is only one image, imageIndex can be ignored:
    public int getHeight (int imageIndex) throws IIOException
    {
      // Because a PCX file contains only one image, imageIndex must be zero.
      // The private checkIndex() method throws IndexOutOfBoundsException if
      // imageIndex is not 0.
    
      checkIndex (imageIndex);
    
      // To get the height, the image header must be read. The private
      // readHeader() method does nothing if the header has been read.
    
      readHeader ();
    
      return height;
    }
  • public abstract IIOMetadata getImageMetadata(int imageIndex) returns a javax.imageio.metadata.IIOMetadata object containing metadata associated with the imageIndex-specific image, or null if the reader does not support reading metadata, is set to ignore metadata, or if no metadata is available:
    public IIOMetadata getImageMetadata (int imageIndex)
    {
      // This plug-in ignores image metadata -- metadata about a single image.
    
      return null;
    }
  • public abstract Iterator getImageTypes(int imageIndex) returns a java.util.Iterator containing possible image types, in the form of javax.imageio.ImageTypeSpecifiers, to which the imageIndex image may be decoded. At least one legal image type will be returned:
    public Iterator<ImageTypeSpecifier> getImageTypes (int imageIndex)
      throws IIOException
    {
      checkIndex (imageIndex);
    
      readHeader ();
    
      // Create a List of ImageTypeSpecifiers that identify the possible image
      // types to which the single PCX image can be decoded. An
      // ImageTypeSpecifier is used with ImageReader’s getDestination() method
      // to return an appropriate BufferedImage that contains the decoded
      // image, and is accessed by an application.
    
      java.util.List<ImageTypeSpecifier> l;
      l = new ArrayList<ImageTypeSpecifier> ();
    
      // The PCX reader only uses a single List entry. This entry describes a
      // BufferedImage of TYPE_INT_RGB, which is a commonly used image type.
    
      l.add (ImageTypeSpecifier.
         createFromBufferedImageType (BufferedImage.TYPE_INT_RGB));
    
      // Return an iterator that retrieves elements from the list.
    
      return l.iterator ();
    }
  • public abstract int getNumImages(boolean allowSearch) returns the number of images, not including thumbnails (one or more small preview images stored alongside the main image; used by some image formats for identifying image files quickly, without the need to decode the entire image), available from the current input source.

    The allowSearch parameter determines whether a search may be performed to obtain the number of images. This search is performed if allowSearch is true, the image file format stores multiple images, and this format (GIF 89a, for example) does not store a count of images. If a search is required and allowSearch is false, -1 returns:

    public int getNumImages (boolean allowSearch)
    {
      // A PCX file stores only one image.
    
      return 1;
    }
  • public abstract IIOMetadata getStreamMetadata() returns an IIOMetadata object representing the metadata associated with the input source as a whole (that is, not associated with any particular image), or null if the reader does not support reading metadata, is set to ignore metadata, or if no metadata is available:
    public IIOMetadata getStreamMetadata ()
    {
      // This plug-in ignores stream metadata -- metadata about all images in
      // an ImageInputStream or other input source.
    
      return null;
    }
  • public abstract int getWidth(int imageIndex) returns the width of an image from the input source. Some formats, such as GIF 89a, can store multiple images. In these cases, the image whose width is to be returned is identified by the zero-based imageIndex. If there is only one image, imageIndex can be ignored:
    public int getWidth (int imageIndex) throws IIOException
    {
      checkIndex (imageIndex);
    
      readHeader ();
    
      return width;
    }
  • public abstract BufferedImage read(int imageIndex, ImageReadParam param) reads the image indexed by imageIndex and returns it as a java.awt.image.BufferedImage using a supplied ImageReadParam. In addition to the same exceptions as getHeight(), this method throws IllegalArgumentException if param values are illegal:
    public BufferedImage read (int imageIndex, ImageReadParam param)
      throws IOException
    {
      checkIndex (imageIndex);
    
      readHeader ();
    
      // Calculate and return a Rectangle that identifies the region of the
      // source image that should be read:
      //
      // 1. If param is null, the upper-left corner of the region is (0, 0),
      //  and the width and height are specified by the width and height
      //  arguments. In other words, the entire image is read.
      //
      // 2. If param is not null
      //
      //  2.1 If param.getSourceRegion() returns a non-null Rectangle, the
      //    region is calculated as the intersection of param’s Rectangle
      //    and the earlier (0, 0, width, height Rectangle).
      //
      //  2.2 param.getSubsamplingXOffset() is added to the region’s x
      //    coordinate and subtracted from its width.
      //
      //  2.3 param.getSubsamplingYOffset() is added to the region’s y
      //    coordinate and subtracted from its height.
    
      Rectangle sourceRegion = getSourceRegion (param, width, height);
    
      // Source subsampling is used to return a scaled-down source image.
      // Default 1 values for X and Y subsampling indicate that a non-scaled
      // source image will be returned.
    
      int sourceXSubsampling = 1;
      int sourceYSubsampling = 1;
    
      // The final step in reading an image from a source to a destination is
      // to map the source samples in various source bands to destination
      // samples in various destination bands. This lets you return only the
      // red component of an image, for example. Default null values indicate
      // that all source and destination bands are used.
    
      int [] sourceBands = null;
      int [] destinationBands = null;
    
      // The destination offset determines the starting location in the
      // destination where decoded pixels are placed. Default (0, 0) values
      // indicate the upper-left corner.
    
      Point destinationOffset = new Point (0, 0);
    
      // If param is not null, override the source subsampling, source bands,
      // destination bands, and destination offset defaults.
    
      if (param != null)
      {
        sourceXSubsampling = param.getSourceXSubsampling ();
        sourceYSubsampling = param.getSourceYSubsampling ();
        sourceBands = param.getSourceBands ();
        destinationBands = param.getDestinationBands ();
        destinationOffset = param.getDestinationOffset ();
      }
    
      // Obtain a BufferedImage into which decoded pixels will be placed. This
      // destination will be returned to the application.
      //
      // 1. If param is not null
      //
      //  1.1 If param.getDestination() returns a BufferedImage 
      //
      //    1.1.1 Return this BufferedImage
      //
      //    Else
      //
      //    1.1.2 Invoke param.getDestinationType ().
      //
      //    1.1.3 If the returned ImageTypeSpecifier equals 
      //       getImageTypes (0) (see below), return its BufferedImage.
      //
      // 2. If param is null or a BufferedImage has not been obtained
      //
      //  2.1 Return getImageTypes (0)’s BufferedImage.
    
      BufferedImage dst = getDestination (param, getImageTypes (0), width,
                        height);
    
      // Verify that the number of source bands and destination bands, as
      // specified by param, are the same. If param is null, 3 is compared
      // with dst.getSampleModel ().getNumBands (), which must also equal 3.
      // An IllegalArgumentException is thrown if the number of source bands
      // differs from the number of destination bands.
    
      checkReadParamBandSettings (param, 3,
                    dst.getSampleModel ().getNumBands ());
    
      // Create a WritableRaster for the source.
    
      WritableRaster wrSrc = Raster.createBandedRaster (DataBuffer.TYPE_BYTE,
                               width, 1, 3,
                               new Point (0, 0));
      byte [][] banks;
      banks = ((DataBufferByte) wrSrc.getDataBuffer ()).getBankData ();
    
      // Create a WritableRaster for the destination.
    
      WritableRaster wrDst = dst.getRaster ();
    
      // Identify destination rectangle for clipping purposes. Only source
      // pixels within this rectangle are copied to the destination.
    
      int dstMinX = wrDst.getMinX ();
      int dstMaxX = dstMinX + wrDst.getWidth () - 1;
      int dstMinY = wrDst.getMinY ();
      int dstMaxY = dstMinY + wrDst.getHeight () - 1;
    
      // Create a child raster that exposes only the desired source bands.
    
      if (sourceBands != null)
        wrSrc = wrSrc.createWritableChild (0, 0, width, 1, 0, 0,
                         sourceBands);
    
      // Create a child raster that exposes only the desired destination
      // bands.
    
      if (destinationBands != null)
        wrDst = wrDst.createWritableChild (0, 0, wrDst.getWidth (),
                         wrDst.getHeight (), 0, 0,
                         destinationBands);
    
      int srcY = 0;
      try
      {
        int [] pixel = wrSrc.getPixel (0, 0, (int []) null);
    
        for (srcY = 0; srcY < height; srcY++)
        {
          // Read the next row from the PCX file.
    
          readScanline ();
          copyScanlineToBanks (banks);
    
          // Reject rows that lie outside the source region, or which are
          // not part of the subsampling.
    
          if ((srcY < sourceRegion.y) ||
            (srcY >= sourceRegion.y + sourceRegion.height) ||
            (((srcY - sourceRegion.y) % sourceYSubsampling) != 0))
            continue;
    
          // Determine the row’s location in the destination.
    
          int dstY = destinationOffset.y +
                (srcY - sourceRegion.y)/sourceYSubsampling;
          if (dstY < dstMinY)
            continue; // The row is above the top of the destination
                 // rectangle.
    
          if (dstY > dstMaxY)
            break; // The row is below the bottom of the destination
                // rectangle.
    
          // Copy each subsampled source pixel that fits into the
          // destination rectangle into the destination.
    
          for (int srcX = sourceRegion.x;
             srcX < sourceRegion.x + sourceRegion.width; srcX++)
          {
             if (((srcX - sourceRegion.x) % sourceXSubsampling) != 0)
               continue;
    
             int dstX = destinationOffset.x +
                  (srcX - sourceRegion.x)/sourceXSubsampling;
             if (dstX < dstMinX)
               continue; // The pixel is to the destination
                    // rectangle’s left.
    
             if (dstX > dstMaxX)
               break; // The pixel is to the destination rectangle’s
                  // right.
    
             // Copy the pixel. Sub-banding is automatically handled.
    
             wrSrc.getPixel (srcX, 0, pixel);
             wrDst.setPixel (dstX, dstY, pixel);
          }
        }
      }
      catch (IOException e)
      {
       throw new IIOException ("Error reading line " + srcY +
                   ": " + e.getMessage (), e);
      }
    
      return dst;
    }

Most of the excerpted methods invoke the private checkIndex() method to verify the image index argument. This method throws an IllegalArgumentException if the index is not 0. The private readHeader() method is invoked next to read the PCX header. This method throws javax.image.IIOException (a java.io.IOException subclass) if a read error occurs.

The readHeader() method will throw an IllegalStateException if the input source has not been set. Before an application can obtain information about a PCX image (such as its width) or read the image, it must establish the input source. This task is demonstrated in the Java documentation’s Image I/O tutorial:

Iterator readers = ImageIO.getImageReadersByFormatName("gif");
ImageReader reader = (ImageReader)readers.next();

Object source; // File or InputStream
ImageInputStream iis = ImageIO.createImageInputStream(source);

reader.setInput(iis, true);

The input source (a file or an input stream) is wrapped in a javax.imageio.stream.ImageInputStream instance because the reader may only recognize ImageInputStream as its input source. This limit is due to an SPI’s constructor passing STANDARD_INPUT_TYPE, which specifies an input types array consisting solely of ImageInputStream, to its ImageReaderSpi superclass.

The input source is established by calling one of ImageReader’s three setInput() methods: public void setInput(Object input), public void setInput(Object input, boolean seekForwardOnly), and public void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata).

Parameter input identifies the input source. Parameter seekForwardOnly decides whether image data may only be read in ascending order. Finally, parameter ignoreMetadata decides whether metadata is ignored. The first method defaults to calling the third method with false as the second and third arguments, and the second method defaults to calling the third method with false as the third argument.

The reader plug-in must override one of these methods to save the input source for later use in reading image data. If setInput(Object input) is overridden, the application must call this method to save the input source. Similarly, if setInput(Object input, boolean seekForwardOnly) is overridden, the application calls this method.

Or the application can call setInput(Object input) because the default implementations for the first two methods call the third method with false as the second and/or third arguments, and because an overridden method must first call its superclass variant. To allow an application to call any method, I’ve overridden setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata):

public void setInput (Object input, boolean seekForwardOnly,
           boolean ignoreMetadata)
{
  super.setInput (input, seekForwardOnly, ignoreMetadata);

  if (input == null)
  {
    this.stream = null;
    return;
  }

  // The input source must be an ImageInputStream because the originating
  // provider -- the PCXImageReaderSpi class -- passes STANDARD_INPUT_TYPE
  // -- an array consisting only of ImageInputStream -- to its superclass
  // in its constructor call.

  if (input instanceof ImageInputStream)
    this.stream = (ImageInputStream) input;
  else
    throw new IllegalArgumentException ("ImageInputStream expected!");
}
  • + Share This
  • 🔖 Save To Your Account