ImageReader.java 63.5 KB
Newer Older
Tom Tromey committed
1
/* ImageReader.java -- Decodes raster images.
2
   Copyright (C) 2004, 2005  Free Software Foundation, Inc.
Tom Tromey committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */


package javax.imageio;

41 42
import java.awt.Point;
import java.awt.Rectangle;
Tom Tromey committed
43 44
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
45
import java.awt.image.RenderedImage;
Tom Tromey committed
46 47 48 49 50
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
51 52 53
import java.util.ResourceBundle;
import java.util.MissingResourceException;
import java.util.Set;
Tom Tromey committed
54 55 56 57 58 59 60 61

import javax.imageio.event.IIOReadProgressListener;
import javax.imageio.event.IIOReadUpdateListener;
import javax.imageio.event.IIOReadWarningListener;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.stream.ImageInputStream;

62 63 64 65 66 67 68 69 70 71 72 73 74 75
/**
 * A class for decoding images within the ImageIO framework.
 *
 * An ImageReader for a given format is instantiated by an
 * ImageReaderSpi for that format.  ImageReaderSpis are registered
 * with the IIORegistry.
 *
 * The ImageReader API supports reading animated images that may have
 * multiple frames; to support such images many methods take an index
 * parameter.
 *
 * Images may also be read in multiple passes, where each successive
 * pass increases the level of detail in the destination image.
 */
Tom Tromey committed
76 77 78 79
public abstract class ImageReader
{
  private boolean aborted;

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
  /**
   * All locales available for localization of warning messages, or
   * null if localization is not supported.
   */
  protected Locale[] availableLocales = null;

  /**
   * true if the input source does not require metadata to be read,
   * false otherwise.
   */
  protected boolean ignoreMetadata = false;

  /**
   * An ImageInputStream from which image data is read.
   */
  protected Object input = null;

  /**
   * The current locale used to localize warning messages, or null if
   * no locale has been set.
   */
  protected Locale locale = null;

  /**
   * The minimum index at which data can be read.  Constantly 0 if
   * seekForwardOnly is false, always increasing if seekForwardOnly is
   * true.
   */
  protected int minIndex = 0;

  /**
   * The image reader SPI that instantiated this reader.
   */
  protected ImageReaderSpi originatingProvider = null;

  /**
   * A list of installed progress listeners.  Initially null, meaning
   * no installed listeners.
   */
119
  protected List<IIOReadProgressListener> progressListeners = null;
120 121 122 123 124 125 126 127 128 129 130 131

  /**
   * true if this reader should only read data further ahead in the
   * stream than its current location.  false if it can read backwards
   * in the stream.  If this is true then caching can be avoided.
   */
  protected boolean seekForwardOnly = false;

  /**
   * A list of installed update listeners.  Initially null, meaning no
   * installed listeners.
   */
132
  protected List<IIOReadUpdateListener> updateListeners = null;
133 134 135 136 137

  /**
   * A list of installed warning listeners.  Initially null, meaning
   * no installed listeners.
   */
138
  protected List<IIOReadWarningListener> warningListeners = null;
139 140 141 142 143

  /**
   * A list of warning locales corresponding with the list of
   * installed warning listeners.  Initially null, meaning no locales.
   */
144
  protected List<Locale> warningLocales = null;
145 146 147 148 149 150 151

  /**
   * Construct an image reader.
   *
   * @param originatingProvider the provider that is constructing this
   * image reader, or null
   */
Tom Tromey committed
152 153 154 155 156
  protected ImageReader(ImageReaderSpi originatingProvider)
  {
    this.originatingProvider = originatingProvider;
  }

157 158 159 160 161 162 163
  /**
   * Request that reading be aborted.  The unread contents of the
   * image will be undefined.
   *
   * Readers should clear the abort flag before starting a read
   * operation, then poll it periodically during the read operation.
   */
Tom Tromey committed
164 165 166 167 168
  public void abort()
  {
    aborted = true;
  }

169 170 171 172 173 174
  /**
   * Check if the abort flag is set.
   *
   * @return true if the current read operation should be aborted,
   * false otherwise
   */
Tom Tromey committed
175 176 177 178 179
  protected boolean abortRequested()
  {
    return aborted;
  }

180 181 182 183 184 185
  /**
   * Install a read progress listener.  This method will return
   * immediately if listener is null.
   *
   * @param listener a read progress listener or null
   */
Tom Tromey committed
186 187 188 189
  public void addIIOReadProgressListener(IIOReadProgressListener listener)
  {
    if (listener == null)
      return;
190 191 192
    if (progressListeners == null)
      progressListeners = new ArrayList ();
    progressListeners.add(listener);
Tom Tromey committed
193 194
  }

195 196 197 198 199 200
  /**
   * Install a read update listener.  This method will return
   * immediately if listener is null.
   *
   * @param listener a read update listener
   */
Tom Tromey committed
201 202 203 204
  public void addIIOReadUpdateListener(IIOReadUpdateListener listener)
  {
    if (listener == null)
      return;
205 206 207
    if (updateListeners == null)
      updateListeners = new ArrayList ();
    updateListeners.add(listener);
Tom Tromey committed
208
  }
209 210 211 212 213 214 215 216 217 218

  /**
   * Install a read warning listener.  This method will return
   * immediately if listener is null.  Warning messages sent to this
   * listener will be localized using the current locale.  If the
   * current locale is null then this reader will select a sensible
   * default.
   *
   * @param listener a read warning listener
   */
Tom Tromey committed
219 220 221 222
  public void addIIOReadWarningListener(IIOReadWarningListener listener)
  {
    if (listener == null)
      return;
223 224 225
    if (warningListeners == null)
      warningListeners = new ArrayList ();
    warningListeners.add(listener);
Tom Tromey committed
226 227
  }

228 229 230 231 232 233 234
  /**
   * Check if this reader can handle raster data.  Determines whether
   * or not readRaster and readTileRaster throw
   * UnsupportedOperationException.
   *
   * @return true if this reader supports raster data, false if not
   */
Tom Tromey committed
235 236 237 238 239
  public boolean canReadRaster()
  {
    return false;
  }

240 241 242
  /**
   * Clear the abort flag.
   */
Tom Tromey committed
243 244 245 246
  protected void clearAbortRequest()
  {
    aborted = false;
  }
247 248 249 250 251 252 253 254

  /**
   * Releases any resources allocated to this object.  Subsequent
   * calls to methods on this object will produce undefined results.
   *
   * The default implementation does nothing; subclasses should use
   * this method ensure that native resources are released.
   */
Tom Tromey committed
255 256 257 258
  public void dispose()
  {
    // The default implementation does nothing.
  }
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273

  /**
   * Returns the aspect ratio of this image, the ration of its width
   * to its height.  The aspect ratio is useful when resizing an image
   * while keeping its proportions constant.
   *
   * @param imageIndex the frame index
   *
   * @return the image's aspect ratio
   *
   * @exception IllegalStateException if input is null
   * @exception IndexOutOfBoundsException if the frame index is
   * out-of-bounds
   * @exception IOException if a read error occurs
   */
Tom Tromey committed
274 275 276
  public float getAspectRatio(int imageIndex)
    throws IOException
  {
277 278 279
    if (input == null)
      throw new IllegalStateException("input is null");

Tom Tromey committed
280 281 282
    return (float) (getWidth(imageIndex) / getHeight(imageIndex));
  }

283 284 285 286 287 288
  /**
   * Retrieve the available locales.  Return null if no locales are
   * available or a clone of availableLocales.
   *
   * @return an array of locales or null
   */
Tom Tromey committed
289 290 291 292
  public Locale[] getAvailableLocales()
  {
    if (availableLocales == null)
      return null;
293

Tom Tromey committed
294 295 296
    return (Locale[]) availableLocales.clone();
  }

297 298 299 300 301 302 303 304
  /**
   * Retrieve the default read parameters for this reader's image
   * format.
   *
   * The default implementation returns new ImageReadParam().
   *
   * @return image reading parameters
   */
Tom Tromey committed
305 306 307 308 309
  public ImageReadParam getDefaultReadParam()
  {
    return new ImageReadParam();
  }

310 311 312 313 314 315 316
  /**
   * Retrieve the format of the input source.
   *
   * @return the input source format name
   *
   * @exception IOException if a read error occurs
   */
Tom Tromey committed
317 318 319 320 321 322
  public String getFormatName()
    throws IOException
  {
    return originatingProvider.getFormatNames()[0];
  }

323 324 325 326 327 328 329 330 331 332 333 334 335
  /**
   * Get the height of the input image in pixels.  If the input image
   * is resizable then a default height is returned.
   *
   * @param imageIndex the frame index
   *
   * @return the height of the input image
   *
   * @exception IllegalStateException if input has not been set
   * @exception IndexOutOfBoundsException if the frame index is
   * out-of-bounds
   * @exception IOException if a read error occurs
   */
Tom Tromey committed
336 337 338
  public abstract int getHeight(int imageIndex)
    throws IOException;

339 340 341 342 343 344 345 346 347 348 349 350 351 352
  /**
   * Get the metadata associated with this image.  If the reader is
   * set to ignore metadata or does not support reading metadata, or
   * if no metadata is available then null is returned.
   *
   * @param imageIndex the frame index
   *
   * @return a metadata object, or null
   *
   * @exception IllegalStateException if input has not been set
   * @exception IndexOutOfBoundsException if the frame index is
   * out-of-bounds
   * @exception IOException if a read error occurs
   */
Tom Tromey committed
353 354 355
  public abstract IIOMetadata getImageMetadata(int imageIndex)
    throws IOException;

356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
  /**
   * Get an iterator over the collection of image types into which
   * this reader can decode image data.  This method is guaranteed to
   * return at least one valid image type specifier.
   *
   * The elements of the iterator should be ordered; the first element
   * should be the most appropriate image type for this decoder,
   * followed by the second-most appropriate, and so on.
   *
   * @param imageIndex the frame index
   *
   * @return an iterator over a collection of image type specifiers
   *
   * @exception IllegalStateException if input has not been set
   * @exception IndexOutOfBoundsException if the frame index is
   * out-of-bounds
   * @exception IOException if a read error occurs
   */
374
  public abstract Iterator<ImageTypeSpecifier> getImageTypes(int imageIndex)
Tom Tromey committed
375 376
    throws IOException;

377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
  /**
   * Set the input source to the given object, specify whether this
   * reader should be allowed to read input from the data stream more
   * than once, and specify whether this reader should ignore metadata
   * in the input stream.  The input source must be set before many
   * methods can be called on this reader. (see all ImageReader
   * methods that throw IllegalStateException).  If input is null then
   * the current input source will be removed.
   *
   * Unless this reader has direct access with imaging hardware, input
   * should be an ImageInputStream.
   *
   * @param input the input source object
   * @param seekForwardOnly true if this reader should be allowed to
   * read input from the data stream more than once, false otherwise
   * @param ignoreMetadata true if this reader should ignore metadata
   * associated with the input source, false otherwise
   *
   * @exception IllegalArgumentException if input is not a valid input
   * source for this reader and is not an ImageInputStream
   */
Tom Tromey committed
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
  public void setInput(Object input,
                       boolean seekForwardOnly,
                       boolean ignoreMetadata)
  {
    Class[] okClasses = originatingProvider.getInputTypes();
    if (okClasses == null)
      {
        if (!(input instanceof ImageInputStream))
          throw new IllegalArgumentException();
      }
    else
      {
        boolean classOk = false;
        for (int i = 0; i < okClasses.length; ++i)
          if (okClasses[i].isInstance(input))
            classOk = true;
        if (!classOk)
          throw new IllegalArgumentException();
      }

    this.input = input;
    this.seekForwardOnly = seekForwardOnly;
    this.ignoreMetadata = ignoreMetadata;
    this.minIndex = 0;
  }

424 425 426 427 428 429 430 431
  /**
   * Set the input source to the given object and specify whether this
   * reader should be allowed to read input from the data stream more
   * than once.  The input source must be set before many methods can
   * be called on this reader. (see all ImageReader methods that throw
   * IllegalStateException).  If input is null then the current input
   * source will be removed.
   *
432
   * @param in the input source object
433 434 435 436 437 438
   * @param seekForwardOnly true if this reader should be allowed to
   * read input from the data stream more than once, false otherwise
   *
   * @exception IllegalArgumentException if input is not a valid input
   * source for this reader and is not an ImageInputStream
   */
Tom Tromey committed
439 440 441 442 443
  public void setInput(Object in, boolean seekForwardOnly)
  {
    setInput(in, seekForwardOnly, false);
  }

444 445 446 447 448 449 450 451 452 453 454 455
  /**
   * Set the input source to the given object.  The input source must
   * be set before many methods can be called on this reader. (see all
   * ImageReader methods that throw IllegalStateException).  If input
   * is null then the current input source will be removed.
   *
   * @param input the input source object
   *
   * @exception IllegalArgumentException if input is not a valid input
   * source for this reader and is not an ImageInputStream
   */
  public void setInput(Object input)
Tom Tromey committed
456
  {
457
    setInput(input, false, false);
Tom Tromey committed
458 459
  }

460 461 462 463 464 465
  /**
   * Get this reader's image input source.  null is returned if the
   * image source has not been set.
   *
   * @return an image input source object, or null
   */
Tom Tromey committed
466 467 468 469 470
  public Object getInput()
  {
    return input;
  }

471 472 473 474 475 476
  /**
   * Get this reader's locale.  null is returned if the locale has not
   * been set.
   *
   * @return this reader's locale, or null
   */
Tom Tromey committed
477 478 479 480 481
  public Locale getLocale()
  {
    return locale;
  }

482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
  /**
   * Return the number of images available from the image input
   * source, not including thumbnails.  This method will return 1
   * unless this reader is reading an animated image.
   *
   * Certain multi-image formats do not encode the total number of
   * images.  When reading images in those formats it may be necessary
   * to repeatedly call read, incrementing the image index at each
   * call, until an IndexOutOfBoundsException is thrown.
   *
   * The allowSearch parameter determines whether all images must be
   * available at all times.  When allowSearch is false, getNumImages
   * will return -1 if the total number of images is unknown.
   * Otherwise this method returns the number of images.
   *
   * @param allowSearch true if all images should be available at
   * once, false otherwise
   *
   * @return -1 if allowSearch is false and the total number of images
   * is currently unknown, or the number of images
   *
   * @exception IllegalStateException if input has not been set, or if
   * seekForwardOnly is true
   * @exception IOException if a read error occurs
   */
Tom Tromey committed
507 508 509
  public abstract int getNumImages(boolean allowSearch)
    throws IOException;

510 511 512 513 514 515 516
  /**
   * Get the number of thumbnails associated with an image.
   *
   * @param imageIndex the frame index
   *
   * @return the number of thumbnails associated with this image
   */
Tom Tromey committed
517 518 519 520 521 522
  public int getNumThumbnails(int imageIndex)
    throws IOException
  {
    return 0;
  }

523 524 525 526 527
  /**
   * Get the ImageReaderSpi that created this reader or null.
   *
   * @return an ImageReaderSpi, or null
   */
Tom Tromey committed
528 529 530 531 532
  public ImageReaderSpi getOriginatingProvider()
  {
    return originatingProvider;
  }

533 534 535 536 537 538 539 540 541 542 543 544
  /**
   * Get the metadata associated with the image being read.  If the
   * reader is set to ignore metadata or does not support reading
   * metadata, or if no metadata is available then null is returned.
   * This method returns metadata associated with the entirety of the
   * image data, whereas getImageMetadata(int) returns metadata
   * associated with a frame within a multi-image data stream.
   *
   * @return metadata associated with the image being read, or null
   *
   * @exception IOException if a read error occurs
   */
Tom Tromey committed
545 546 547
  public abstract IIOMetadata getStreamMetadata()
    throws IOException;

548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
  /**
   * Get the height of a thumbnail image.
   *
   * @param imageIndex the frame index
   * @param thumbnailIndex the thumbnail index
   *
   * @return the height of the thumbnail image
   *
   * @exception UnsupportedOperationException if this reader does not
   * support thumbnails
   * @exception IllegalStateException if input is null
   * @exception IndexOutOfBoundsException if either index is
   * out-of-bounds
   * @exception IOException if a read error occurs
   */
Tom Tromey committed
563 564 565 566 567 568
  public int getThumbnailHeight(int imageIndex, int thumbnailIndex)
    throws IOException
  {
    return readThumbnail(imageIndex, thumbnailIndex).getHeight();
  }

569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
  /**
   * Get the width of a thumbnail image.
   *
   * @param imageIndex the frame index
   * @param thumbnailIndex the thumbnail index
   *
   * @return the width of the thumbnail image
   *
   * @exception UnsupportedOperationException if this reader does not
   * support thumbnails
   * @exception IllegalStateException if input is null
   * @exception IndexOutOfBoundsException if either index is
   * out-of-bounds
   * @exception IOException if a read error occurs
   */
Tom Tromey committed
584 585 586 587 588 589
  public int getThumbnailWidth(int imageIndex, int thumbnailIndex)
    throws IOException
  {
    return readThumbnail(imageIndex, thumbnailIndex).getWidth();
  }

590 591 592 593 594 595 596 597 598 599 600 601 602 603
  /**
   * Get the X coordinate in pixels of the top-left corner of the
   * first tile in this image.
   *
   * @param imageIndex the frame index
   *
   * @return the X coordinate of this image's first tile
   *
   * @exception IllegalStateException if input is needed but the input
   * source is not set
   * @exception IndexOutOfBoundsException if the frame index is
   * out-of-bounds
   * @exception IOException if a read error occurs
   */
Tom Tromey committed
604 605 606 607 608 609
  public int getTileGridXOffset(int imageIndex)
    throws IOException
  {
    return 0;
  }

610 611 612 613 614 615 616 617 618 619 620 621 622 623
  /**
   * Get the Y coordinate in pixels of the top-left corner of the
   * first tile in this image.
   *
   * @param imageIndex the frame index
   *
   * @return the Y coordinate of this image's first tile
   *
   * @exception IllegalStateException if input is needed but the input
   * source is not set
   * @exception IndexOutOfBoundsException if the frame index is
   * out-of-bounds
   * @exception IOException if a read error occurs
   */
Tom Tromey committed
624 625 626 627 628 629
  public int getTileGridYOffset(int imageIndex)
    throws IOException
  {
    return 0;
  }

630 631 632 633 634 635 636 637 638 639 640 641
  /**
   * Get the height of an image tile.
   *
   * @param imageIndex the frame index
   *
   * @return the tile height for the given image
   *
   * @exception IllegalStateException if input is null
   * @exception IndexOutOfBoundsException if the frame index is
   * out-of-bounds
   * @exception IOException if a read error occurs
   */
Tom Tromey committed
642 643 644 645 646 647
  public int getTileHeight(int imageIndex)
    throws IOException
  {
    return getHeight(imageIndex);
  }

648 649 650 651 652 653 654 655 656 657 658 659
  /**
   * Get the width of an image tile.
   *
   * @param imageIndex the frame index
   *
   * @return the tile width for the given image
   *
   * @exception IllegalStateException if input is null
   * @exception IndexOutOfBoundsException if the frame index is
   * out-of-bounds
   * @exception IOException if a read error occurs
   */
Tom Tromey committed
660 661 662 663 664 665
  public int getTileWidth(int imageIndex)
    throws IOException
  {
    return getWidth(imageIndex);
  }

666 667 668 669 670 671 672 673 674 675 676 677 678
  /**
   * Get the width of the input image in pixels.  If the input image
   * is resizable then a default width is returned.
   *
   * @param imageIndex the image's index
   *
   * @return the width of the input image
   *
   * @exception IllegalStateException if input has not been set
   * @exception IndexOutOfBoundsException if the frame index is
   * out-of-bounds
   * @exception IOException if a read error occurs
   */
Tom Tromey committed
679 680 681
  public abstract int getWidth(int imageIndex)
    throws IOException;

682 683 684 685 686 687 688 689 690 691 692
  /**
   * Check whether or not the given image has thumbnails associated
   * with it.
   *
   * @return true if the given image has thumbnails, false otherwise
   *
   * @exception IllegalStateException if input is null
   * @exception IndexOutOfBoundsException if the frame index is
   * out-of-bounds
   * @exception IOException if a read error occurs
   */
Tom Tromey committed
693 694 695 696 697 698
  public boolean hasThumbnails(int imageIndex)
    throws IOException
  {
    return getNumThumbnails(imageIndex) > 0;
  }

699 700 701 702 703 704
  /**
   * Check if this image reader ignores metadata.  This method simply
   * returns the value of ignoreMetadata.
   *
   * @return true if metadata is being ignored, false otherwise
   */
Tom Tromey committed
705 706 707 708 709
  public boolean isIgnoringMetadata()
  {
    return ignoreMetadata;
  }

710 711 712 713 714 715 716 717 718 719 720 721 722 723
  /**
   * Check if the given image is sub-divided into equal-sized
   * non-overlapping pixel rectangles.
   *
   * A reader may expose tiling in the underlying format, hide it, or
   * simulate tiling even if the underlying format is not tiled.
   *
   * @return true if the given image is tiled, false otherwise
   *
   * @exception IllegalStateException if input is null
   * @exception IndexOutOfBoundsException if the frame index is
   * out-of-bounds
   * @exception IOException if a read error occurs
   */
Tom Tromey committed
724 725 726 727 728 729
  public boolean isImageTiled(int imageIndex)
    throws IOException
  {
    return false;
  }

730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
  /**
   * Check if all pixels in this image are readily accessible.  This
   * method should return false for compressed formats.  The return
   * value is a hint as to the efficiency of certain image reader
   * operations.
   *
   * @param imageIndex the frame index
   *
   * @return true if random pixel access is fast, false otherwise
   *
   * @exception IllegalStateException if input is null and it is
   * needed to determine the return value
   * @exception IndexOutOfBoundsException if the frame index is
   * out-of-bounds but the frame data must be accessed to determine
   * the return value
   * @exception IOException if a read error occurs
   */
Tom Tromey committed
747 748 749 750 751 752
  public boolean isRandomAccessEasy(int imageIndex)
    throws IOException
  {
    return false;
  }

753 754 755 756 757 758 759
  /**
   * Check if this image reader may only seek forward within the input
   * stream.
   *
   * @return true if this reader may only seek forward, false
   * otherwise
   */
Tom Tromey committed
760 761 762 763 764
  public boolean isSeekForwardOnly()
  {
    return seekForwardOnly;
  }

765 766 767 768
  /**
   * Notifies all installed read progress listeners that image loading
   * has completed by calling their imageComplete methods.
   */
Tom Tromey committed
769 770
  protected void processImageComplete()
  {
771
    if (progressListeners != null)
Tom Tromey committed
772
      {
773 774 775 776 777 778 779 780
        Iterator it = progressListeners.iterator();

        while (it.hasNext())
          {
            IIOReadProgressListener listener =
              (IIOReadProgressListener) it.next();
            listener.imageComplete (this);
          }
Tom Tromey committed
781 782 783
      }
  }

784 785 786 787 788 789 790 791
  /**
   * Notifies all installed read progress listeners that a certain
   * percentage of the image has been loaded, by calling their
   * imageProgress methods.
   *
   * @param percentageDone the percentage of image data that has been
   * loaded
   */
Tom Tromey committed
792 793
  protected void processImageProgress(float percentageDone)
  {
794
     if (progressListeners != null)
Tom Tromey committed
795
      {
796 797 798 799 800 801 802 803
        Iterator it = progressListeners.iterator();

        while (it.hasNext())
          {
            IIOReadProgressListener listener =
              (IIOReadProgressListener) it.next();
            listener.imageProgress(this, percentageDone);
          }
Tom Tromey committed
804 805
      }
  }
806 807 808 809 810 811 812 813
  /**
   * Notifies all installed read progress listeners, by calling their
   * imageStarted methods, that image loading has started on the given
   * image.
   *
   * @param imageIndex the frame index of the image that has started
   * loading
   */
Tom Tromey committed
814 815
  protected void processImageStarted(int imageIndex)
  {
816
     if (progressListeners != null)
Tom Tromey committed
817
      {
818 819 820 821 822 823 824 825
        Iterator it = progressListeners.iterator();

        while (it.hasNext())
          {
            IIOReadProgressListener listener =
              (IIOReadProgressListener) it.next();
            listener.imageStarted(this, imageIndex);
          }
Tom Tromey committed
826 827 828
      }
  }

829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
  /**
   * Notifies all installed read update listeners, by calling their
   * imageUpdate methods, that the set of samples has changed.
   *
   * @param image the buffered image that is being updated
   * @param minX the X coordinate of the top-left pixel in this pass
   * @param minY the Y coordinate of the top-left pixel in this pass
   * @param width the total width of the rectangle covered by this
   * pass, including skipped pixels
   * @param height the total height of the rectangle covered by this
   * pass, including skipped pixels
   * @param periodX the horizontal sample interval
   * @param periodY the vertical sample interval
   * @param bands the affected bands in the destination
   */
Tom Tromey committed
844
  protected void processImageUpdate(BufferedImage image, int minX, int minY,
845 846
                                    int width, int height, int periodX,
                                    int periodY, int[] bands)
Tom Tromey committed
847
  {
848
    if (updateListeners != null)
Tom Tromey committed
849
      {
850 851 852 853 854 855 856 857
        Iterator it = updateListeners.iterator();

        while (it.hasNext())
          {
            IIOReadUpdateListener listener = (IIOReadUpdateListener) it.next();
            listener.imageUpdate(this, image, minX, minY, width, height,
                                 periodX, periodY, bands);
          }
Tom Tromey committed
858 859 860
      }
  }

861 862 863 864 865 866 867
  /**
   * Notifies all installed update progress listeners, by calling
   * their passComplete methods, that a progressive pass has
   * completed.
   *
   * @param image the image that has being updated
   */
Tom Tromey committed
868 869
  protected void processPassComplete(BufferedImage image)
  {
870
    if (updateListeners != null)
Tom Tromey committed
871
      {
872
        Iterator it = updateListeners.iterator();
873

874 875 876 877 878
        while (it.hasNext())
          {
            IIOReadUpdateListener listener = (IIOReadUpdateListener) it.next();
            listener.passComplete(this, image);
          }
Tom Tromey committed
879 880 881
      }
  }

882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
  /**
   * Notifies all installed read update listeners, by calling their
   * passStarted methods, that a new pass has begun.
   *
   * @param image the buffered image that is being updated
   * @param pass the current pass number
   * @param minPass the pass at which decoding will begin
   * @param maxPass the pass at which decoding will end
   * @param minX the X coordinate of the top-left pixel in this pass
   * @param minY the Y coordinate of the top-left pixel in this pass
   * @param width the total width of the rectangle covered by this
   * pass, including skipped pixels
   * @param height the total height of the rectangle covered by this
   * pass, including skipped pixels
   * @param periodX the horizontal sample interval
   * @param periodY the vertical sample interval
   * @param bands the affected bands in the destination
   */
Tom Tromey committed
900
  protected void processPassStarted(BufferedImage image, int pass, int minPass,
901 902
                                    int maxPass, int minX, int minY,
                                    int periodX, int periodY, int[] bands)
Tom Tromey committed
903
  {
904
    if (updateListeners != null)
Tom Tromey committed
905
      {
906 907 908 909 910 911 912 913
        Iterator it = updateListeners.iterator();

        while (it.hasNext())
          {
            IIOReadUpdateListener listener = (IIOReadUpdateListener) it.next();
            listener.passStarted(this, image, pass, minPass, maxPass, minX,
                                 minY, periodX, periodY, bands);
          }
Tom Tromey committed
914 915 916
      }
  }

917 918 919 920
  /**
   * Notifies all installed read progress listeners that image loading
   * has been aborted by calling their readAborted methods.
   */
Tom Tromey committed
921 922
  protected void processReadAborted()
  {
923
     if (progressListeners != null)
Tom Tromey committed
924
      {
925 926 927 928 929 930 931 932
        Iterator it = progressListeners.iterator();

        while (it.hasNext())
          {
            IIOReadProgressListener listener =
              (IIOReadProgressListener) it.next();
            listener.readAborted(this);
          }
Tom Tromey committed
933 934
      }
  }
935 936 937 938 939
  /**
   * Notifies all installed read progress listeners, by calling their
   * sequenceComplete methods, that a sequence of images has completed
   * loading.
   */
Tom Tromey committed
940 941
  protected void processSequenceComplete()
  {
942
     if (progressListeners != null)
Tom Tromey committed
943
      {
944 945 946 947 948 949 950 951
        Iterator it = progressListeners.iterator();

        while (it.hasNext())
          {
            IIOReadProgressListener listener =
              (IIOReadProgressListener) it.next();
            listener.sequenceComplete(this);
          }
Tom Tromey committed
952 953 954
      }
  }

955 956 957 958 959 960 961
  /**
   * Notifies all installed read progress listeners, by calling their
   * sequenceStarted methods, a sequence of images has started
   * loading.
   *
   * @param minIndex the index of the first image in the sequence
   */
Tom Tromey committed
962 963 964
  protected void processSequenceStarted(int minIndex)
  {

965
    if (progressListeners != null)
Tom Tromey committed
966
      {
967 968 969 970 971 972 973 974
        Iterator it = progressListeners.iterator();

        while (it.hasNext())
          {
            IIOReadProgressListener listener =
              (IIOReadProgressListener) it.next();
            listener.sequenceStarted(this, minIndex);
          }
Tom Tromey committed
975 976 977
      }
  }

978 979 980 981 982
  /**
   * Notifies all installed read progress listeners, by calling their
   * thumbnailComplete methods, that a thumbnail has completed
   * loading.
   */
Tom Tromey committed
983 984
  protected void processThumbnailComplete()
  {
985
    if (progressListeners != null)
Tom Tromey committed
986
      {
987 988 989 990 991 992 993 994
        Iterator it = progressListeners.iterator();

        while (it.hasNext())
          {
            IIOReadProgressListener listener =
              (IIOReadProgressListener) it.next();
            listener.thumbnailComplete(this);
          }
Tom Tromey committed
995 996 997
      }
  }

998 999 1000 1001 1002 1003 1004
  /**
   * Notifies all installed update progress listeners, by calling
   * their thumbnailPassComplete methods, that a progressive pass has
   * completed on a thumbnail.
   *
   * @param thumbnail the thumbnail that has being updated
   */
Tom Tromey committed
1005 1006
  protected void processThumbnailPassComplete(BufferedImage thumbnail)
  {
1007
    if (updateListeners != null)
Tom Tromey committed
1008
      {
1009
        Iterator it = updateListeners.iterator();
1010

1011 1012 1013 1014 1015
        while (it.hasNext())
          {
            IIOReadUpdateListener listener = (IIOReadUpdateListener) it.next();
            listener.thumbnailPassComplete(this, thumbnail);
          }
Tom Tromey committed
1016 1017 1018
      }
  }

1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
  /**
   * Notifies all installed read update listeners, by calling their
   * thumbnailPassStarted methods, that a new pass has begun.
   *
   * @param thumbnail the thumbnail that is being updated
   * @param pass the current pass number
   * @param minPass the pass at which decoding will begin
   * @param maxPass the pass at which decoding will end
   * @param minX the X coordinate of the top-left pixel in this pass
   * @param minY the Y coordinate of the top-left pixel in this pass
   * @param width the total width of the rectangle covered by this
   * pass, including skipped pixels
   * @param height the total height of the rectangle covered by this
   * pass, including skipped pixels
   * @param periodX the horizontal sample interval
   * @param periodY the vertical sample interval
   * @param bands the affected bands in the destination
   */
Tom Tromey committed
1037
  protected void processThumbnailPassStarted(BufferedImage thumbnail, int pass,
1038 1039 1040
                                             int minPass, int maxPass, int minX,
                                             int minY, int periodX, int periodY,
                                             int[] bands)
Tom Tromey committed
1041
  {
1042
    if (updateListeners != null)
Tom Tromey committed
1043
      {
1044 1045 1046 1047 1048 1049 1050 1051 1052
        Iterator it = updateListeners.iterator();

        while (it.hasNext())
          {
            IIOReadUpdateListener listener = (IIOReadUpdateListener) it.next();
            listener.thumbnailPassStarted(this, thumbnail, pass, minPass,
                                          maxPass, minX, minY, periodX,
                                          periodY, bands);
          }
Tom Tromey committed
1053 1054
      }
  }
1055 1056 1057 1058 1059 1060 1061 1062 1063

  /**
   * Notifies all installed read progress listeners that a certain
   * percentage of a thumbnail has been loaded, by calling their
   * thumbnailProgress methods.
   *
   * @param percentageDone the percentage of thumbnail data that has
   * been loaded
   */
Tom Tromey committed
1064 1065
  protected void processThumbnailProgress(float percentageDone)
  {
1066
    if (progressListeners != null)
Tom Tromey committed
1067
      {
1068 1069 1070 1071 1072 1073 1074 1075
        Iterator it = progressListeners.iterator();

        while (it.hasNext())
          {
            IIOReadProgressListener listener =
              (IIOReadProgressListener) it.next();
            listener.thumbnailProgress(this, percentageDone);
          }
Tom Tromey committed
1076 1077 1078
      }
  }

1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
  /**
   * Notifies all installed read progress listeners, by calling their
   * imageStarted methods, that thumbnail loading has started on the
   * given thumbnail of the given image.
   *
   * @param imageIndex the frame index of the image one of who's
   * thumbnails has started loading
   * @param thumbnailIndex the index of the thumbnail that has started
   * loading
   */
Tom Tromey committed
1089 1090
  protected void processThumbnailStarted(int imageIndex, int thumbnailIndex)
  {
1091
    if (progressListeners != null)
Tom Tromey committed
1092
      {
1093 1094 1095 1096 1097 1098 1099 1100
        Iterator it = progressListeners.iterator();

        while (it.hasNext())
          {
            IIOReadProgressListener listener =
              (IIOReadProgressListener) it.next();
            listener.thumbnailStarted(this, imageIndex, thumbnailIndex);
          }
Tom Tromey committed
1101 1102 1103
      }
  }

1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
  /**
   * Notifies all installed read update listeners, by calling their
   * thumbnailUpdate methods, that the set of samples has changed.
   *
   * @param image the buffered image that is being updated
   * @param minX the X coordinate of the top-left pixel in this pass
   * @param minY the Y coordinate of the top-left pixel in this pass
   * @param width the total width of the rectangle covered by this
   * pass, including skipped pixels
   * @param height the total height of the rectangle covered by this
   * pass, including skipped pixels
   * @param periodX the horizontal sample interval
   * @param periodY the vertical sample interval
   * @param bands the affected bands in the destination
   */
Tom Tromey committed
1119
  protected void processThumbnailUpdate(BufferedImage image, int minX, int minY,
1120 1121
                                        int width, int height, int periodX,
                                        int periodY, int[] bands)
Tom Tromey committed
1122
  {
1123
    if (updateListeners != null)
Tom Tromey committed
1124
      {
1125 1126 1127 1128 1129 1130 1131 1132
        Iterator it = updateListeners.iterator();

        while (it.hasNext())
          {
            IIOReadUpdateListener listener = (IIOReadUpdateListener) it.next();
            listener.thumbnailUpdate(this, image, minX, minY, width, height,
                                     periodX, periodY, bands);
          }
Tom Tromey committed
1133 1134 1135
      }
  }

1136 1137 1138 1139 1140 1141 1142 1143
  /**
   * Notifies all installed warning listeners, by calling their
   * warningOccurred methods, that a warning message has been raised.
   *
   * @param warning the warning message
   *
   * @exception IllegalArgumentException if warning is null
   */
Tom Tromey committed
1144 1145
  protected void processWarningOccurred(String warning)
  {
1146 1147 1148 1149
    if (warning == null)
      throw new IllegalArgumentException ("null argument");
    if (warningListeners != null)
      {
1150 1151 1152 1153 1154 1155 1156 1157
        Iterator it = warningListeners.iterator();

        while (it.hasNext())
          {
            IIOReadWarningListener listener =
              (IIOReadWarningListener) it.next();
            listener.warningOccurred(this, warning);
          }
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
      }
  }

  /**
   * Notify all installed warning listeners, by calling their
   * warningOccurred methods, that a warning message has been raised.
   * The warning message is retrieved from a resource bundle, using
   * the given basename and keyword.
   *
   * @param baseName the basename of the resource from which to
   * retrieve the warning message
   * @param keyword the keyword used to retrieve the warning from the
   * resource bundle
   *
   * @exception IllegalArgumentException if either baseName or keyword
   * is null
   * @exception IllegalArgumentException if no resource bundle is
   * found using baseName
   * @exception IllegalArgumentException if the given keyword produces
   * no results from the resource bundle
   * @exception IllegalArgumentException if the retrieved object is
   * not a String
   */
  protected void processWarningOccurred(String baseName,
1182
                                        String keyword)
1183 1184 1185 1186 1187 1188 1189 1190
  {
    if (baseName == null || keyword == null)
      throw new IllegalArgumentException ("null argument");

    ResourceBundle b = null;

    try
      {
1191
        b = ResourceBundle.getBundle(baseName, getLocale());
1192 1193 1194
      }
    catch (MissingResourceException e)
      {
1195
        throw new IllegalArgumentException ("no resource bundle found");
1196 1197 1198
      }

    Object str = null;
Tom Tromey committed
1199

1200
    try
Tom Tromey committed
1201
      {
1202
        str = b.getObject(keyword);
1203 1204 1205
      }
    catch (MissingResourceException e)
      {
1206
        throw new IllegalArgumentException ("no results found for keyword");
1207 1208 1209 1210 1211 1212 1213 1214 1215
      }

    if (! (str instanceof String))
      throw new IllegalArgumentException ("retrieved object not a String");

    String warning = (String) str;

    if (warningListeners != null)
      {
1216 1217 1218 1219 1220 1221 1222 1223
        Iterator it = warningListeners.iterator();

        while (it.hasNext())
          {
            IIOReadWarningListener listener =
              (IIOReadWarningListener) it.next();
            listener.warningOccurred(this, warning);
          }
Tom Tromey committed
1224 1225 1226
      }
  }

1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
  /**
   * Read the given frame into a buffered image using the given read
   * parameters.  Listeners will be notified of image loading progress
   * and warnings.
   *
   * @param imageIndex the index of the frame to read
   * @param param the image read parameters to use when reading
   *
   * @return a buffered image
   *
   * @exception IllegalStateException if input is null
   * @exception IndexOutOfBoundsException if the frame index is
   * out-of-bounds
   * @exception IOException if a read error occurs
   */
Tom Tromey committed
1242 1243 1244
  public abstract BufferedImage read(int imageIndex, ImageReadParam param)
    throws IOException;

1245 1246 1247 1248 1249 1250
  /**
   * Check if this reader supports reading thumbnails.
   *
   * @return true if this reader supports reading thumbnails, false
   * otherwise
   */
Tom Tromey committed
1251 1252 1253 1254 1255
  public boolean readerSupportsThumbnails()
  {
    return false;
  }

1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
  /**
   * Read raw raster data.  The image type specifier in param is
   * ignored but all other parameters are used.  Offset parameters are
   * translated into the raster's coordinate space.  This method may
   * be implemented by image readers that want to provide direct
   * access to raw image data.
   *
   * @param imageIndex the frame index
   * @param param the image read parameters
   *
   * @return a raster containing the read image data
   *
   * @exception UnsupportedOperationException if this reader doesn't
   * support rasters
   * @exception IllegalStateException if input is null
   * @exception IndexOutOfBoundsException if the frame index is
   * out-of-bounds
   * @exception IOException if a read error occurs
   */
Tom Tromey committed
1275 1276 1277 1278 1279 1280
  public Raster readRaster(int imageIndex, ImageReadParam param)
    throws IOException
  {
    throw new UnsupportedOperationException();
  }

1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
  /**
   * Read a thumbnail.
   *
   * @param imageIndex the frame index
   * @param thumbnailIndex the thumbnail index
   *
   * @return a buffered image of the thumbnail
   *
   * @exception UnsupportedOperationException if this reader doesn't
   * support thumbnails
   * @exception IllegalStateException if input is null
   * @exception IndexOutOfBoundsException if either the frame index or
   * the thumbnail index is out-of-bounds
   * @exception IOException if a read error occurs
1295
   *
1296
   */
Tom Tromey committed
1297 1298 1299 1300 1301 1302
  public BufferedImage readThumbnail(int imageIndex, int thumbnailIndex)
    throws IOException
  {
    throw new UnsupportedOperationException();
  }

1303 1304 1305
  /**
   * Uninstall all read progress listeners.
   */
Tom Tromey committed
1306 1307
  public void removeAllIIOReadProgressListeners()
  {
1308
    progressListeners = null;
Tom Tromey committed
1309 1310
  }

1311 1312 1313
  /**
   * Uninstall all read update listeners.
   */
Tom Tromey committed
1314 1315
  public void removeAllIIOReadUpdateListeners()
  {
1316
    updateListeners = null;
Tom Tromey committed
1317 1318
  }

1319 1320 1321
  /**
   * Uninstall all read warning listeners.
   */
Tom Tromey committed
1322 1323
  public void removeAllIIOReadWarningListeners()
  {
1324
    warningListeners = null;
Tom Tromey committed
1325
  }
1326 1327 1328 1329 1330 1331

  /**
   * Uninstall the given read progress listener.
   *
   * @param listener the listener to remove
   */
1332
  public void removeIIOReadProgressListener(IIOReadProgressListener listener)
Tom Tromey committed
1333 1334 1335
  {
    if (listener == null)
      return;
1336 1337
    if (progressListeners != null)
      {
1338
        progressListeners.remove(listener);
1339
      }
Tom Tromey committed
1340
  }
1341 1342 1343 1344 1345 1346

  /**
   * Uninstall the given read update listener.
   *
   * @param listener the listener to remove
   */
1347
  public void removeIIOReadUpdateListener(IIOReadUpdateListener listener)
Tom Tromey committed
1348 1349 1350
  {
    if (listener == null)
      return;
1351 1352 1353

    if (updateListeners != null)
      {
1354
        updateListeners.remove(listener);
1355
      }
Tom Tromey committed
1356
  }
1357 1358 1359 1360 1361 1362

  /**
   * Uninstall the given read warning listener.
   *
   * @param listener the listener to remove
   */
Tom Tromey committed
1363 1364 1365 1366
  public void removeIIOReadWarningListener(IIOReadWarningListener listener)
  {
    if (listener == null)
      return;
1367 1368
    if (warningListeners != null)
      {
1369
        warningListeners.remove(listener);
1370
      }
Tom Tromey committed
1371
  }
1372 1373 1374 1375 1376 1377

  /**
   * Set the current locale or use the default locale.
   *
   * @param locale the locale to set, or null
   */
Tom Tromey committed
1378 1379 1380 1381
  public void setLocale(Locale locale)
  {
    if (locale != null)
      {
1382 1383
        // Check if its a valid locale.
        boolean found = false;
Tom Tromey committed
1384

1385 1386 1387 1388
        if (availableLocales != null)
          for (int i = availableLocales.length - 1; i >= 0; --i)
            if (availableLocales[i].equals(locale))
              found = true;
Tom Tromey committed
1389

1390 1391
        if (! found)
          throw new IllegalArgumentException("looale not available");
Tom Tromey committed
1392 1393 1394 1395
      }

    this.locale = locale;
  }
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413

  /**
   * Check that the given read parameters have valid source and
   * destination band settings.  If the param.getSourceBands() returns
   * null, the array is assumed to include all band indices, 0 to
   * numSrcBands - 1; likewise if param.getDestinationBands() returns
   * null, it is assumed to be an array containing indices 0 to
   * numDstBands - 1.  A failure will cause this method to throw
   * IllegalArgumentException.
   *
   * @param param the image parameters to check
   * @param numSrcBands the number of input source bands
   * @param numDstBands the number of ouput destination bands
   *
   * @exception IllegalArgumentException if either the given source or
   * destination band indices are invalid
   */
  protected static void checkReadParamBandSettings(ImageReadParam param,
1414 1415
                                                   int numSrcBands,
                                                   int numDstBands)
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
  {
    int[] srcBands = param.getSourceBands();
    int[] dstBands = param.getDestinationBands();
    boolean lengthsDiffer = false;
    boolean srcOOB = false;
    boolean dstOOB = false;

    if (srcBands == null)
      {
        if (dstBands == null)
          {
            if (numSrcBands != numDstBands)
              lengthsDiffer = true;
          }
        else
          {
            if (numSrcBands != dstBands.length)
              lengthsDiffer = true;

            for (int i = 0; i < dstBands.length; i++)
              if (dstBands[i] > numSrcBands - 1)
                {
                  dstOOB = true;
                  break;
                }
          }
      }
    else
      {
        if (dstBands == null)
          {
            if (srcBands.length != numDstBands)
              lengthsDiffer = true;

            for (int i = 0; i < srcBands.length; i++)
              if (srcBands[i] > numDstBands - 1)
                {
                  srcOOB = true;
                  break;
                }
          }
        else
          {
            if (srcBands.length != dstBands.length)
              lengthsDiffer = true;

            for (int i = 0; i < srcBands.length; i++)
              if (srcBands[i] > numDstBands - 1)
                {
                  srcOOB = true;
                  break;
                }

            for (int i = 0; i < dstBands.length; i++)
              if (dstBands[i] > numSrcBands - 1)
                {
                  dstOOB = true;
                  break;
                }
          }
      }

    if (lengthsDiffer)
      throw new IllegalArgumentException ("array lengths differ");

    if (srcOOB)
      throw new IllegalArgumentException ("source band index"
                                          + " out-of-bounds");

    if (dstOOB)
      throw new IllegalArgumentException ("destination band index"
                                          + " out-of-bounds");
  }

  /**
   * Calcluate the source and destination regions that will be read
   * from and written to, given image parameters and/or a destination
   * buffered image.  The source region will be clipped if any of its
   * bounds are outside the destination region.  Clipping will account
   * for subsampling and destination offsets.  Likewise, the
   * destination region is clipped to the given destination image, if
   * it is not null, using the given image parameters, if they are not
   * null.  IllegalArgumentException is thrown if either region will
   * contain 0 pixels after clipping.
   *
1501
   * @param param read parameters, or null
1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
   * @param srcWidth the width of the source image
   * @param srcHeight the height of the source image
   * @param image the destination image, or null
   * @param srcRegion a rectangle whose values will be set to the
   * clipped source region
   * @param destRegion a rectangle whose values will be set to the
   * clipped destination region
   *
   * @exception IllegalArgumentException if either srcRegion or
   * destRegion is null
   * @exception IllegalArgumentException if either of the calculated
   * regions is empty
   */
  protected static void computeRegions (ImageReadParam param,
1516 1517 1518 1519 1520
                                        int srcWidth,
                                        int srcHeight,
                                        BufferedImage image,
                                        Rectangle srcRegion,
                                        Rectangle destRegion)
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
  {
    if (srcRegion == null || destRegion == null)
      throw new IllegalArgumentException ("null region");

    if (srcWidth == 0 || srcHeight == 0)
      throw new IllegalArgumentException ("zero-sized region");

    srcRegion = getSourceRegion(param, srcWidth, srcHeight);
    if (image != null)
      destRegion = new Rectangle (0, 0, image.getWidth(), image.getHeight());
    else
      destRegion = new Rectangle (0, 0, srcWidth, srcHeight);

    if (param != null)
      {
        Point offset = param.getDestinationOffset();

        if (offset.x < 0)
          {
            srcRegion.x -= offset.x;
            srcRegion.width += offset.x;
          }
        if (offset.y < 0)
          {
            srcRegion.y -= offset.y;
            srcRegion.height += offset.y;
          }

        srcRegion.width = srcRegion.width > destRegion.width
          ? destRegion.width : srcRegion.width;
        srcRegion.height = srcRegion.height > destRegion.height
          ? destRegion.height : srcRegion.height;

        if (offset.x >= 0)
          {
            destRegion.x += offset.x;
            destRegion.width -= offset.x;
          }
        if (offset.y >= 0)
          {
            destRegion.y += offset.y;
            destRegion.height -= offset.y;
          }
      }

    if (srcRegion.isEmpty() || destRegion.isEmpty())
      throw new IllegalArgumentException ("zero-sized region");
  }

  /**
   * Return a suitable destination buffered image.  If
   * param.getDestination() is non-null, then it is returned,
   * otherwise a buffered image is created using
   * param.getDestinationType() if it is non-null and also in the
   * given imageTypes collection, or the first element of imageTypes
   * otherwise.
   *
   * @param param image read parameters from which a destination image
   * or image type is retrieved, or null
   * @param imageTypes a collection of legal image types
   * @param width the width of the source image
   * @param height the height of the source image
   *
   * @return a suitable destination buffered image
   *
   * @exception IIOException if param.getDestinationType() does not
   * return an image type in imageTypes
   * @exception IllegalArgumentException if imageTypes is null or
   * empty, or if a non-ImageTypeSpecifier object is retrieved from
   * imageTypes
   * @exception IllegalArgumentException if the resulting destination
   * region is empty
   * @exception IllegalArgumentException if the product of width and
   * height is greater than Integer.MAX_VALUE
   */
  protected static BufferedImage getDestination (ImageReadParam param,
1597 1598 1599
                                                 Iterator<ImageTypeSpecifier> imageTypes,
                                                 int width,
                                                 int height)
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
    throws IIOException
  {
    if (imageTypes == null || !imageTypes.hasNext())
      throw new IllegalArgumentException ("imageTypes null or empty");

    if (width < 0 || height < 0)
      throw new IllegalArgumentException ("negative dimension");

    // test for overflow
    if (width * height < Math.min (width, height))
      throw new IllegalArgumentException ("width * height > Integer.MAX_VALUE");

    BufferedImage dest = null;
    ImageTypeSpecifier destType = null;

    if (param != null)
      {
        dest = param.getDestination ();
        if (dest == null)
          {
            ImageTypeSpecifier type = param.getDestinationType();
            if (type != null)
              {
                Iterator it = imageTypes;

                while (it.hasNext())
                  {
                    Object o = it.next ();
                    if (! (o instanceof ImageTypeSpecifier))
                      throw new IllegalArgumentException ("non-ImageTypeSpecifier object");

                    ImageTypeSpecifier t = (ImageTypeSpecifier) o;
                    if (t.equals (type))
                      {
                        dest = t.createBufferedImage (width, height);
                        break;
                      }
                    if (destType == null)
                      throw new IIOException ("invalid destination type");

                  }
              }
          }
      }
    if (dest == null)
      {
        Rectangle srcRegion = new Rectangle ();
        Rectangle destRegion = new Rectangle ();

        computeRegions (param, width, height, null, srcRegion, destRegion);

        if (destRegion.isEmpty())
          throw new IllegalArgumentException ("destination region empty");

        if (destType == null)
          {
            Object o = imageTypes.next();
            if (! (o instanceof ImageTypeSpecifier))
              throw new IllegalArgumentException ("non-ImageTypeSpecifier"
                                                  + " object");

            dest = ((ImageTypeSpecifier) o).createBufferedImage
              (destRegion.width, destRegion.height);
          }
        else
          dest = destType.createBufferedImage
            (destRegion.width, destRegion.height);
      }
    return dest;
  }

  /**
   * Get the metadata associated with this image.  If the reader is
   * set to ignore metadata or does not support reading metadata, or
   * if no metadata is available then null is returned.
   *
   * This more specific version of getImageMetadata(int) can be used
   * to restrict metadata retrieval to specific formats and node
   * names, which can limit the amount of data that needs to be
   * processed.
   *
   * @param imageIndex the frame index
   * @param formatName the format of metadata requested
   * @param nodeNames a set of Strings specifiying node names to be
   * retrieved
   *
   * @return a metadata object, or null
   *
   * @exception IllegalStateException if input has not been set
   * @exception IndexOutOfBoundsException if the frame index is
   * out-of-bounds
   * @exception IllegalArgumentException if formatName is null
   * @exception IllegalArgumentException if nodeNames is null
   * @exception IOException if a read error occurs
   */
  public IIOMetadata getImageMetadata (int imageIndex,
                                       String formatName,
1697
                                       Set<String> nodeNames)
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
    throws IOException
  {
    if (formatName == null || nodeNames == null)
      throw new IllegalArgumentException ("null argument");

    return getImageMetadata (imageIndex);
  }

  /**
   * Get the index at which the next image will be read.  If
   * seekForwardOnly is true then the returned value will increase
   * monotonically each time an image frame is read.  If
   * seekForwardOnly is false then the returned value will always be
   * 0.
   *
   * @return the current frame index
   */
  public int getMinIndex()
  {
    return minIndex;
  }

  /**
   * Get the image type specifier that most closely represents the
   * internal data representation used by this reader.  This value
   * should be included in the return value of getImageTypes.
   *
   * @param imageIndex the frame index
   *
   * @return an image type specifier
   *
   * @exception IllegalStateException if input has not been set
   * @exception IndexOutOfBoundsException if the frame index is
   * out-of-bounds
   * @exception IOException if a read error occurs
   */
  public ImageTypeSpecifier getRawImageType (int imageIndex)
    throws IOException
  {
1737
    return getImageTypes(imageIndex).next();
1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
  }

  /**
   * Calculate a source region based on the given source image
   * dimensions and parameters.  Subsampling offsets and a source
   * region are taken from the given image read parameters and used to
   * clip the given image dimensions, returning a new rectangular
   * region as a result.
   *
   * @param param image parameters, or null
   * @param srcWidth the width of the source image
   * @param srcHeight the height of the source image
   *
   * @return a clipped rectangle
   */
  protected static Rectangle getSourceRegion (ImageReadParam param,
1754 1755
                                              int srcWidth,
                                              int srcHeight)
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
  {
    Rectangle clippedRegion = new Rectangle (0, 0, srcWidth, srcHeight);

    if (param != null)
      {
        Rectangle srcRegion = param.getSourceRegion();

        if (srcRegion != null)
          {
            clippedRegion.x = srcRegion.x > clippedRegion.x
              ? srcRegion.x : clippedRegion.x;
            clippedRegion.y = srcRegion.y > clippedRegion.y
              ? srcRegion.y : clippedRegion.y;
            clippedRegion.width = srcRegion.width > clippedRegion.width
              ? srcRegion.width : clippedRegion.width;
            clippedRegion.height = srcRegion.height > clippedRegion.height
              ? srcRegion.height : clippedRegion.height;
          }

        int xOffset = param.getSubsamplingXOffset();

        clippedRegion.x += xOffset;
        clippedRegion.width -= xOffset;

        int yOffset = param.getSubsamplingYOffset();

        clippedRegion.y += yOffset;
        clippedRegion.height -= yOffset;
      }
    return clippedRegion;
  }

  /**
   * Get the metadata associated with the image being read.  If the
   * reader is set to ignore metadata or does not support reading
   * metadata, or if no metadata is available then null is returned.
   * This method returns metadata associated with the entirety of the
   * image data, whereas getStreamMetadata() returns metadata
   * associated with a frame within a multi-image data stream.
   *
   * This more specific version of getStreamMetadata() can be used to
   * restrict metadata retrieval to specific formats and node names,
   * which can limit the amount of data that needs to be processed.
   *
   * @param formatName the format of metadata requested
   * @param nodeNames a set of Strings specifiying node names to be
   * retrieved
   *
   * @return metadata associated with the image being read, or null
   *
   * @exception IllegalArgumentException if formatName is null
   * @exception IllegalArgumentException if nodeNames is null
   * @exception IOException if a read error occurs
   */
  public IIOMetadata getStreamMetadata (String formatName,
1811
                                        Set<String> nodeNames)
1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
    throws IOException
  {
    if (formatName == null || nodeNames == null)
      throw new IllegalArgumentException ("null argument");

    return getStreamMetadata();
  }

  /**
   * Read the given frame all at once, using default image read
   * parameters, and return a buffered image.
   *
   * The returned image will be formatted according to the
   * currently-preferred image type specifier.
   *
   * Installed read progress listeners, update progress listeners and
   * warning listeners will be notified of read progress, changes in
   * sample sets and warnings respectively.
   *
1831
   * @param imageIndex the index of the image frame to read
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857
   *
   * @return a buffered image
   *
   * @exception IllegalStateException if input has not been set
   * @exception IndexOutOfBoundsException if the frame index is
   * out-of-bounds
   * @exception IOException if a read error occurs
   */
  public BufferedImage read (int imageIndex)
    throws IOException
  {
    return read (imageIndex, null);
  }

  /**
   * Read the given frame all at once, using the given image read
   * parameters, and return an IIOImage.  The IIOImage will contain a
   * buffered image as returned by getDestination.
   *
   * Installed read progress listeners, update progress listeners and
   * warning listeners will be notified of read progress, changes in
   * sample sets and warnings respectively.
   *
   * The source and destination band settings are checked with a call
   * to checkReadParamBandSettings.
   *
1858 1859
   * @param imageIndex the index of the image frame to read
   * @param param the image read parameters
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
   *
   * @return an IIOImage
   *
   * @exception IllegalStateException if input has not been set
   * @exception IndexOutOfBoundsException if the frame index is
   * out-of-bounds
   * @exception IllegalArgumentException if param.getSourceBands() and
   * param.getDestinationBands() are incompatible
   * @exception IllegalArgumentException if either the source or
   * destination image regions are empty
   * @exception IOException if a read error occurs
   */
  public IIOImage readAll (int imageIndex,
1873
                           ImageReadParam param)
1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904
    throws IOException
  {
    checkReadParamBandSettings (param,
                                param.getSourceBands().length,
                                param.getDestinationBands().length);

    List l = new ArrayList ();

    for (int i = 0; i < getNumThumbnails (imageIndex); i++)
      l.add (readThumbnail(imageIndex, i));

    return new IIOImage (getDestination(param, getImageTypes(imageIndex),
                                        getWidth(imageIndex),
                                        getHeight(imageIndex)),
                         l,
                         getImageMetadata (imageIndex));
  }

  /**
   * Read all image frames all at once, using the given image read
   * parameters iterator, and return an iterator over a collection of
   * IIOImages.  Each IIOImage in the collection will contain a
   * buffered image as returned by getDestination.
   *
   * Installed read progress listeners, update progress listeners and
   * warning listeners will be notified of read progress, changes in
   * sample sets and warnings respectively.
   *
   * Each set of source and destination band settings are checked with
   * a call to checkReadParamBandSettings.
   *
1905
   * @param params iterator over the image read parameters
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
   *
   * @return an IIOImage
   *
   * @exception IllegalStateException if input has not been set
   * @exception IllegalArgumentException if a non-ImageReadParam is
   * found in params
   * @exception IllegalArgumentException if param.getSourceBands() and
   * param.getDestinationBands() are incompatible
   * @exception IllegalArgumentException if either the source or
   * destination image regions are empty
   * @exception IOException if a read error occurs
   */
1918
  public Iterator<IIOImage> readAll (Iterator<? extends ImageReadParam> params)
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
    throws IOException
  {
    List l = new ArrayList ();
    int index = 0;

    while (params.hasNext())
      {
        if (params != null && ! (params instanceof ImageReadParam))
          throw new IllegalArgumentException ("non-ImageReadParam found");

        l.add (readAll(index++, (ImageReadParam) params.next ()));
      }

    return l.iterator();
  }

  /**
   * Read a rendered image.  This is a more general counterpart to
   * read (int, ImageReadParam).  All image data may not be read
   * before this method returns and so listeners will not necessarily
   * be notified.
   *
1941 1942
   * @param imageIndex the index of the image frame to read
   * @param param the image read parameters
1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955
   *
   * @return a rendered image
   *
   * @exception IllegalStateException if input is null
   * @exception IndexOutOfBoundsException if the frame index is
   * out-of-bounds
   * @exception IllegalArgumentException if param.getSourceBands() and
   * param.getDestinationBands() are incompatible
   * @exception IllegalArgumentException if either the source or
   * destination image regions are empty
   * @exception IOException if a read error occurs
   */
  public RenderedImage readAsRenderedImage (int imageIndex,
1956
                                            ImageReadParam param)
1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
    throws IOException
  {
    return read (imageIndex, param);
  }

  /**
   * Read the given tile into a buffered image.  If the tile
   * coordinates are out-of-bounds an exception is thrown.  If the
   * image is not tiled then the coordinates 0, 0 are expected and the
   * entire image will be read.
   *
   * @param imageIndex the frame index
   * @param tileX the horizontal tile coordinate
   * @param tileY the vertical tile coordinate
   *
   * @return the contents of the tile as a buffered image
   *
   * @exception IllegalStateException if input is null
   * @exception IndexOutOfBoundsException if the frame index is
   * out-of-bounds
   * @exception IllegalArgumentException if the tile coordinates are
   * out-of-bounds
   * @exception IOException if a read error occurs
   */
  public BufferedImage readTile (int imageIndex, int tileX, int tileY)
    throws IOException
  {
    if (tileX != 0 || tileY != 0)
      throw new IllegalArgumentException ("tileX not 0 or tileY not 0");

    return read (imageIndex);
  }

  /**
   * Read the given tile into a raster containing the raw image data.
   * If the tile coordinates are out-of-bounds an exception is thrown.
   * If the image is not tiled then the coordinates 0, 0 are expected
   * and the entire image will be read.
   *
   * @param imageIndex the frame index
   * @param tileX the horizontal tile coordinate
   * @param tileY the vertical tile coordinate
   *
   * @return the contents of the tile as a raster
   *
   * @exception UnsupportedOperationException if rasters are not
   * supported
   * @exception IllegalStateException if input is null
   * @exception IndexOutOfBoundsException if the frame index is
   * out-of-bounds
   * @exception IllegalArgumentException if the tile coordinates are
   * out-of-bounds
   * @exception IOException if a read error occurs
   */
  public Raster readTileRaster (int imageIndex, int tileX, int tileY)
    throws IOException
  {
    if (!canReadRaster())
      throw new UnsupportedOperationException ("cannot read rasters");

    if (tileX != 0 || tileY != 0)
      throw new IllegalArgumentException ("tileX not 0 or tileY not 0");

    return readRaster (imageIndex, null);
  }

  /**
   * Reset this reader's internal state.
   */
  public void reset ()
  {
    setInput (null, false);
    setLocale (null);
    removeAllIIOReadUpdateListeners ();
    removeAllIIOReadWarningListeners ();
    removeAllIIOReadProgressListeners ();
    clearAbortRequest ();
  }
Tom Tromey committed
2035
}