1 /*
   2  * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.imageio.plugins.png;
  27 
  28 import java.awt.Point;
  29 import java.awt.Rectangle;
  30 import java.awt.color.ColorSpace;
  31 import java.awt.image.BufferedImage;
  32 import java.awt.image.DataBuffer;
  33 import java.awt.image.DataBufferByte;
  34 import java.awt.image.DataBufferUShort;
  35 import java.awt.image.Raster;
  36 import java.awt.image.WritableRaster;
  37 import java.io.BufferedInputStream;
  38 import java.io.ByteArrayInputStream;
  39 import java.io.DataInputStream;
  40 import java.io.EOFException;
  41 import java.io.InputStream;
  42 import java.io.IOException;
  43 import java.io.SequenceInputStream;
  44 import java.util.ArrayList;
  45 import java.util.Arrays;
  46 import java.util.Enumeration;
  47 import java.util.Iterator;
  48 import java.util.zip.Inflater;
  49 import java.util.zip.InflaterInputStream;
  50 import javax.imageio.IIOException;
  51 import javax.imageio.ImageReader;
  52 import javax.imageio.ImageReadParam;
  53 import javax.imageio.ImageTypeSpecifier;
  54 import javax.imageio.metadata.IIOMetadata;
  55 import javax.imageio.spi.ImageReaderSpi;
  56 import javax.imageio.stream.ImageInputStream;
  57 import com.sun.imageio.plugins.common.InputStreamAdapter;
  58 import com.sun.imageio.plugins.common.ReaderUtil;
  59 import com.sun.imageio.plugins.common.SubImageInputStream;
  60 import java.io.ByteArrayOutputStream;
  61 import sun.awt.image.ByteInterleavedRaster;
  62 
  63 class PNGImageDataEnumeration implements Enumeration<InputStream> {
  64 
  65     boolean firstTime = true;
  66     ImageInputStream stream;
  67     int length;
  68 
  69     public PNGImageDataEnumeration(ImageInputStream stream)
  70         throws IOException {
  71         this.stream = stream;
  72         this.length = stream.readInt();
  73         int type = stream.readInt(); // skip chunk type
  74     }
  75 
  76     public InputStream nextElement() {
  77         try {
  78             firstTime = false;
  79             ImageInputStream iis = new SubImageInputStream(stream, length);
  80             return new InputStreamAdapter(iis);
  81         } catch (IOException e) {
  82             return null;
  83         }
  84     }
  85 
  86     public boolean hasMoreElements() {
  87         if (firstTime) {
  88             return true;
  89         }
  90 
  91         try {
  92             int crc = stream.readInt();
  93             this.length = stream.readInt();
  94             int type = stream.readInt();
  95             if (type == PNGImageReader.IDAT_TYPE) {
  96                 return true;
  97             } else {
  98                 return false;
  99             }
 100         } catch (IOException e) {
 101             return false;
 102         }
 103     }
 104 }
 105 
 106 public class PNGImageReader extends ImageReader {
 107 
 108     /*
 109      * Note: The following chunk type constants are autogenerated.  Each
 110      * one is derived from the ASCII values of its 4-character name.  For
 111      * example, IHDR_TYPE is calculated as follows:
 112      *            ('I' << 24) | ('H' << 16) | ('D' << 8) | 'R'
 113      */
 114 
 115     // Critical chunks
 116     static final int IHDR_TYPE = 0x49484452;
 117     static final int PLTE_TYPE = 0x504c5445;
 118     static final int IDAT_TYPE = 0x49444154;
 119     static final int IEND_TYPE = 0x49454e44;
 120 
 121     // Ancillary chunks
 122     static final int bKGD_TYPE = 0x624b4744;
 123     static final int cHRM_TYPE = 0x6348524d;
 124     static final int gAMA_TYPE = 0x67414d41;
 125     static final int hIST_TYPE = 0x68495354;
 126     static final int iCCP_TYPE = 0x69434350;
 127     static final int iTXt_TYPE = 0x69545874;
 128     static final int pHYs_TYPE = 0x70485973;
 129     static final int sBIT_TYPE = 0x73424954;
 130     static final int sPLT_TYPE = 0x73504c54;
 131     static final int sRGB_TYPE = 0x73524742;
 132     static final int tEXt_TYPE = 0x74455874;
 133     static final int tIME_TYPE = 0x74494d45;
 134     static final int tRNS_TYPE = 0x74524e53;
 135     static final int zTXt_TYPE = 0x7a545874;
 136 
 137     static final int PNG_COLOR_GRAY = 0;
 138     static final int PNG_COLOR_RGB = 2;
 139     static final int PNG_COLOR_PALETTE = 3;
 140     static final int PNG_COLOR_GRAY_ALPHA = 4;
 141     static final int PNG_COLOR_RGB_ALPHA = 6;
 142 
 143     // The number of bands by PNG color type
 144     static final int[] inputBandsForColorType = {
 145          1, // gray
 146         -1, // unused
 147          3, // rgb
 148          1, // palette
 149          2, // gray + alpha
 150         -1, // unused
 151          4  // rgb + alpha
 152     };
 153 
 154     static final int PNG_FILTER_NONE = 0;
 155     static final int PNG_FILTER_SUB = 1;
 156     static final int PNG_FILTER_UP = 2;
 157     static final int PNG_FILTER_AVERAGE = 3;
 158     static final int PNG_FILTER_PAETH = 4;
 159 
 160     static final int[] adam7XOffset = { 0, 4, 0, 2, 0, 1, 0 };
 161     static final int[] adam7YOffset = { 0, 0, 4, 0, 2, 0, 1 };
 162     static final int[] adam7XSubsampling = { 8, 8, 4, 4, 2, 2, 1, 1 };
 163     static final int[] adam7YSubsampling = { 8, 8, 8, 4, 4, 2, 2, 1 };
 164 
 165     private static final boolean debug = true;
 166 
 167     ImageInputStream stream = null;
 168 
 169     boolean gotHeader = false;
 170     boolean gotMetadata = false;
 171 
 172     ImageReadParam lastParam = null;
 173 
 174     long imageStartPosition = -1L;
 175 
 176     Rectangle sourceRegion = null;
 177     int sourceXSubsampling = -1;
 178     int sourceYSubsampling = -1;
 179     int sourceMinProgressivePass = 0;
 180     int sourceMaxProgressivePass = 6;
 181     int[] sourceBands = null;
 182     int[] destinationBands = null;
 183     Point destinationOffset = new Point(0, 0);
 184 
 185     PNGMetadata metadata = new PNGMetadata();
 186 
 187     DataInputStream pixelStream = null;
 188 
 189     BufferedImage theImage = null;
 190 
 191     // The number of source pixels processed
 192     int pixelsDone = 0;
 193 
 194     // The total number of pixels in the source image
 195     int totalPixels;
 196 
 197     public PNGImageReader(ImageReaderSpi originatingProvider) {
 198         super(originatingProvider);
 199     }
 200 
 201     public void setInput(Object input,
 202                          boolean seekForwardOnly,
 203                          boolean ignoreMetadata) {
 204         super.setInput(input, seekForwardOnly, ignoreMetadata);
 205         this.stream = (ImageInputStream)input; // Always works
 206 
 207         // Clear all values based on the previous stream contents
 208         resetStreamSettings();
 209     }
 210 
 211     private String readNullTerminatedString(String charset, int maxLen) throws IOException {
 212         ByteArrayOutputStream baos = new ByteArrayOutputStream();
 213         int b;
 214         int count = 0;
 215         while ((maxLen > count++) && ((b = stream.read()) != 0)) {
 216             if (b == -1) throw new EOFException();
 217             baos.write(b);
 218         }
 219         return new String(baos.toByteArray(), charset);
 220     }
 221 
 222     private void readHeader() throws IIOException {
 223         if (gotHeader) {
 224             return;
 225         }
 226         if (stream == null) {
 227             throw new IllegalStateException("Input source not set!");
 228         }
 229 
 230         try {
 231             byte[] signature = new byte[8];
 232             stream.readFully(signature);
 233 
 234             if (signature[0] != (byte)137 ||
 235                 signature[1] != (byte)80 ||
 236                 signature[2] != (byte)78 ||
 237                 signature[3] != (byte)71 ||
 238                 signature[4] != (byte)13 ||
 239                 signature[5] != (byte)10 ||
 240                 signature[6] != (byte)26 ||
 241                 signature[7] != (byte)10) {
 242                 throw new IIOException("Bad PNG signature!");
 243             }
 244 
 245             int IHDR_length = stream.readInt();
 246             if (IHDR_length != 13) {
 247                 throw new IIOException("Bad length for IHDR chunk!");
 248             }
 249             int IHDR_type = stream.readInt();
 250             if (IHDR_type != IHDR_TYPE) {
 251                 throw new IIOException("Bad type for IHDR chunk!");
 252             }
 253 
 254             this.metadata = new PNGMetadata();
 255 
 256             int width = stream.readInt();
 257             int height = stream.readInt();
 258 
 259             // Re-use signature array to bulk-read these unsigned byte values
 260             stream.readFully(signature, 0, 5);
 261             int bitDepth          = signature[0] & 0xff;
 262             int colorType         = signature[1] & 0xff;
 263             int compressionMethod = signature[2] & 0xff;
 264             int filterMethod      = signature[3] & 0xff;
 265             int interlaceMethod   = signature[4] & 0xff;
 266 
 267             // Skip IHDR CRC
 268             stream.skipBytes(4);
 269 
 270             stream.flushBefore(stream.getStreamPosition());
 271 
 272             if (width == 0) {
 273                 throw new IIOException("Image width == 0!");
 274             }
 275             if (height == 0) {
 276                 throw new IIOException("Image height == 0!");
 277             }
 278             if (bitDepth != 1 && bitDepth != 2 && bitDepth != 4 &&
 279                 bitDepth != 8 && bitDepth != 16) {
 280                 throw new IIOException("Bit depth must be 1, 2, 4, 8, or 16!");
 281             }
 282             if (colorType != 0 && colorType != 2 && colorType != 3 &&
 283                 colorType != 4 && colorType != 6) {
 284                 throw new IIOException("Color type must be 0, 2, 3, 4, or 6!");
 285             }
 286             if (colorType == PNG_COLOR_PALETTE && bitDepth == 16) {
 287                 throw new IIOException("Bad color type/bit depth combination!");
 288             }
 289             if ((colorType == PNG_COLOR_RGB ||
 290                  colorType == PNG_COLOR_RGB_ALPHA ||
 291                  colorType == PNG_COLOR_GRAY_ALPHA) &&
 292                 (bitDepth != 8 && bitDepth != 16)) {
 293                 throw new IIOException("Bad color type/bit depth combination!");
 294             }
 295             if (compressionMethod != 0) {
 296                 throw new IIOException("Unknown compression method (not 0)!");
 297             }
 298             if (filterMethod != 0) {
 299                 throw new IIOException("Unknown filter method (not 0)!");
 300             }
 301             if (interlaceMethod != 0 && interlaceMethod != 1) {
 302                 throw new IIOException("Unknown interlace method (not 0 or 1)!");
 303             }
 304 
 305             metadata.IHDR_present = true;
 306             metadata.IHDR_width = width;
 307             metadata.IHDR_height = height;
 308             metadata.IHDR_bitDepth = bitDepth;
 309             metadata.IHDR_colorType = colorType;
 310             metadata.IHDR_compressionMethod = compressionMethod;
 311             metadata.IHDR_filterMethod = filterMethod;
 312             metadata.IHDR_interlaceMethod = interlaceMethod;
 313             gotHeader = true;
 314         } catch (IOException e) {
 315             throw new IIOException("I/O error reading PNG header!", e);
 316         }
 317     }
 318 
 319     private void parse_PLTE_chunk(int chunkLength) throws IOException {
 320         if (metadata.PLTE_present) {
 321             processWarningOccurred(
 322 "A PNG image may not contain more than one PLTE chunk.\n" +
 323 "The chunk wil be ignored.");
 324             return;
 325         } else if (metadata.IHDR_colorType == PNG_COLOR_GRAY ||
 326                    metadata.IHDR_colorType == PNG_COLOR_GRAY_ALPHA) {
 327             processWarningOccurred(
 328 "A PNG gray or gray alpha image cannot have a PLTE chunk.\n" +
 329 "The chunk wil be ignored.");
 330             return;
 331         }
 332 
 333         byte[] palette = new byte[chunkLength];
 334         stream.readFully(palette);
 335 
 336         int numEntries = chunkLength/3;
 337         if (metadata.IHDR_colorType == PNG_COLOR_PALETTE) {
 338             int maxEntries = 1 << metadata.IHDR_bitDepth;
 339             if (numEntries > maxEntries) {
 340                 processWarningOccurred(
 341 "PLTE chunk contains too many entries for bit depth, ignoring extras.");
 342                 numEntries = maxEntries;
 343             }
 344             numEntries = Math.min(numEntries, maxEntries);
 345         }
 346 
 347         // Round array sizes up to 2^2^n
 348         int paletteEntries;
 349         if (numEntries > 16) {
 350             paletteEntries = 256;
 351         } else if (numEntries > 4) {
 352             paletteEntries = 16;
 353         } else if (numEntries > 2) {
 354             paletteEntries = 4;
 355         } else {
 356             paletteEntries = 2;
 357         }
 358 
 359         metadata.PLTE_present = true;
 360         metadata.PLTE_red = new byte[paletteEntries];
 361         metadata.PLTE_green = new byte[paletteEntries];
 362         metadata.PLTE_blue = new byte[paletteEntries];
 363 
 364         int index = 0;
 365         for (int i = 0; i < numEntries; i++) {
 366             metadata.PLTE_red[i] = palette[index++];
 367             metadata.PLTE_green[i] = palette[index++];
 368             metadata.PLTE_blue[i] = palette[index++];
 369         }
 370     }
 371 
 372     private void parse_bKGD_chunk() throws IOException {
 373         if (metadata.IHDR_colorType == PNG_COLOR_PALETTE) {
 374             metadata.bKGD_colorType = PNG_COLOR_PALETTE;
 375             metadata.bKGD_index = stream.readUnsignedByte();
 376         } else if (metadata.IHDR_colorType == PNG_COLOR_GRAY ||
 377                    metadata.IHDR_colorType == PNG_COLOR_GRAY_ALPHA) {
 378             metadata.bKGD_colorType = PNG_COLOR_GRAY;
 379             metadata.bKGD_gray = stream.readUnsignedShort();
 380         } else { // RGB or RGB_ALPHA
 381             metadata.bKGD_colorType = PNG_COLOR_RGB;
 382             metadata.bKGD_red = stream.readUnsignedShort();
 383             metadata.bKGD_green = stream.readUnsignedShort();
 384             metadata.bKGD_blue = stream.readUnsignedShort();
 385         }
 386 
 387         metadata.bKGD_present = true;
 388     }
 389 
 390     private void parse_cHRM_chunk() throws IOException {
 391         metadata.cHRM_whitePointX = stream.readInt();
 392         metadata.cHRM_whitePointY = stream.readInt();
 393         metadata.cHRM_redX = stream.readInt();
 394         metadata.cHRM_redY = stream.readInt();
 395         metadata.cHRM_greenX = stream.readInt();
 396         metadata.cHRM_greenY = stream.readInt();
 397         metadata.cHRM_blueX = stream.readInt();
 398         metadata.cHRM_blueY = stream.readInt();
 399 
 400         metadata.cHRM_present = true;
 401     }
 402 
 403     private void parse_gAMA_chunk() throws IOException {
 404         int gamma = stream.readInt();
 405         metadata.gAMA_gamma = gamma;
 406 
 407         metadata.gAMA_present = true;
 408     }
 409 
 410     private void parse_hIST_chunk(int chunkLength) throws IOException,
 411         IIOException
 412     {
 413         if (!metadata.PLTE_present) {
 414             throw new IIOException("hIST chunk without prior PLTE chunk!");
 415         }
 416 
 417         /* According to PNG specification length of
 418          * hIST chunk is specified in bytes and
 419          * hIST chunk consists of 2 byte elements
 420          * (so we expect length is even).
 421          */
 422         metadata.hIST_histogram = new char[chunkLength/2];
 423         stream.readFully(metadata.hIST_histogram,
 424                          0, metadata.hIST_histogram.length);
 425 
 426         metadata.hIST_present = true;
 427     }
 428 
 429     private void parse_iCCP_chunk(int chunkLength) throws IOException {
 430         String keyword = readNullTerminatedString("ISO-8859-1", 80);
 431         metadata.iCCP_profileName = keyword;
 432 
 433         metadata.iCCP_compressionMethod = stream.readUnsignedByte();
 434 
 435         byte[] compressedProfile =
 436           new byte[chunkLength - keyword.length() - 2];
 437         stream.readFully(compressedProfile);
 438         metadata.iCCP_compressedProfile = compressedProfile;
 439 
 440         metadata.iCCP_present = true;
 441     }
 442 
 443     private void parse_iTXt_chunk(int chunkLength) throws IOException {
 444         long chunkStart = stream.getStreamPosition();
 445 
 446         String keyword = readNullTerminatedString("ISO-8859-1", 80);
 447         metadata.iTXt_keyword.add(keyword);
 448 
 449         int compressionFlag = stream.readUnsignedByte();
 450         metadata.iTXt_compressionFlag.add(Boolean.valueOf(compressionFlag == 1));
 451 
 452         int compressionMethod = stream.readUnsignedByte();
 453         metadata.iTXt_compressionMethod.add(Integer.valueOf(compressionMethod));
 454 
 455         String languageTag = readNullTerminatedString("UTF8", 80);
 456         metadata.iTXt_languageTag.add(languageTag);
 457 
 458         long pos = stream.getStreamPosition();
 459         int maxLen = (int)(chunkStart + chunkLength - pos);
 460         String translatedKeyword =
 461             readNullTerminatedString("UTF8", maxLen);
 462         metadata.iTXt_translatedKeyword.add(translatedKeyword);
 463 
 464         String text;
 465         pos = stream.getStreamPosition();
 466         byte[] b = new byte[(int)(chunkStart + chunkLength - pos)];
 467         stream.readFully(b);
 468 
 469         if (compressionFlag == 1) { // Decompress the text
 470             text = new String(inflate(b), "UTF8");
 471         } else {
 472             text = new String(b, "UTF8");
 473         }
 474         metadata.iTXt_text.add(text);
 475     }
 476 
 477     private void parse_pHYs_chunk() throws IOException {
 478         metadata.pHYs_pixelsPerUnitXAxis = stream.readInt();
 479         metadata.pHYs_pixelsPerUnitYAxis = stream.readInt();
 480         metadata.pHYs_unitSpecifier = stream.readUnsignedByte();
 481 
 482         metadata.pHYs_present = true;
 483     }
 484 
 485     private void parse_sBIT_chunk() throws IOException {
 486         int colorType = metadata.IHDR_colorType;
 487         if (colorType == PNG_COLOR_GRAY ||
 488             colorType == PNG_COLOR_GRAY_ALPHA) {
 489             metadata.sBIT_grayBits = stream.readUnsignedByte();
 490         } else if (colorType == PNG_COLOR_RGB ||
 491                    colorType == PNG_COLOR_PALETTE ||
 492                    colorType == PNG_COLOR_RGB_ALPHA) {
 493             metadata.sBIT_redBits = stream.readUnsignedByte();
 494             metadata.sBIT_greenBits = stream.readUnsignedByte();
 495             metadata.sBIT_blueBits = stream.readUnsignedByte();
 496         }
 497 
 498         if (colorType == PNG_COLOR_GRAY_ALPHA ||
 499             colorType == PNG_COLOR_RGB_ALPHA) {
 500             metadata.sBIT_alphaBits = stream.readUnsignedByte();
 501         }
 502 
 503         metadata.sBIT_colorType = colorType;
 504         metadata.sBIT_present = true;
 505     }
 506 
 507     private void parse_sPLT_chunk(int chunkLength)
 508         throws IOException, IIOException {
 509         metadata.sPLT_paletteName = readNullTerminatedString("ISO-8859-1", 80);
 510         chunkLength -= metadata.sPLT_paletteName.length() + 1;
 511 
 512         int sampleDepth = stream.readUnsignedByte();
 513         metadata.sPLT_sampleDepth = sampleDepth;
 514 
 515         int numEntries = chunkLength/(4*(sampleDepth/8) + 2);
 516         metadata.sPLT_red = new int[numEntries];
 517         metadata.sPLT_green = new int[numEntries];
 518         metadata.sPLT_blue = new int[numEntries];
 519         metadata.sPLT_alpha = new int[numEntries];
 520         metadata.sPLT_frequency = new int[numEntries];
 521 
 522         if (sampleDepth == 8) {
 523             for (int i = 0; i < numEntries; i++) {
 524                 metadata.sPLT_red[i] = stream.readUnsignedByte();
 525                 metadata.sPLT_green[i] = stream.readUnsignedByte();
 526                 metadata.sPLT_blue[i] = stream.readUnsignedByte();
 527                 metadata.sPLT_alpha[i] = stream.readUnsignedByte();
 528                 metadata.sPLT_frequency[i] = stream.readUnsignedShort();
 529             }
 530         } else if (sampleDepth == 16) {
 531             for (int i = 0; i < numEntries; i++) {
 532                 metadata.sPLT_red[i] = stream.readUnsignedShort();
 533                 metadata.sPLT_green[i] = stream.readUnsignedShort();
 534                 metadata.sPLT_blue[i] = stream.readUnsignedShort();
 535                 metadata.sPLT_alpha[i] = stream.readUnsignedShort();
 536                 metadata.sPLT_frequency[i] = stream.readUnsignedShort();
 537             }
 538         } else {
 539             throw new IIOException("sPLT sample depth not 8 or 16!");
 540         }
 541 
 542         metadata.sPLT_present = true;
 543     }
 544 
 545     private void parse_sRGB_chunk() throws IOException {
 546         metadata.sRGB_renderingIntent = stream.readUnsignedByte();
 547 
 548         metadata.sRGB_present = true;
 549     }
 550 
 551     private void parse_tEXt_chunk(int chunkLength) throws IOException {
 552         String keyword = readNullTerminatedString("ISO-8859-1", 80);
 553         metadata.tEXt_keyword.add(keyword);
 554 
 555         byte[] b = new byte[chunkLength - keyword.length() - 1];
 556         stream.readFully(b);
 557         metadata.tEXt_text.add(new String(b, "ISO-8859-1"));
 558     }
 559 
 560     private void parse_tIME_chunk() throws IOException {
 561         metadata.tIME_year = stream.readUnsignedShort();
 562         metadata.tIME_month = stream.readUnsignedByte();
 563         metadata.tIME_day = stream.readUnsignedByte();
 564         metadata.tIME_hour = stream.readUnsignedByte();
 565         metadata.tIME_minute = stream.readUnsignedByte();
 566         metadata.tIME_second = stream.readUnsignedByte();
 567 
 568         metadata.tIME_present = true;
 569     }
 570 
 571     private void parse_tRNS_chunk(int chunkLength) throws IOException {
 572         int colorType = metadata.IHDR_colorType;
 573         if (colorType == PNG_COLOR_PALETTE) {
 574             if (!metadata.PLTE_present) {
 575                 processWarningOccurred(
 576 "tRNS chunk without prior PLTE chunk, ignoring it.");
 577                 return;
 578             }
 579 
 580             // Alpha table may have fewer entries than RGB palette
 581             int maxEntries = metadata.PLTE_red.length;
 582             int numEntries = chunkLength;
 583             if (numEntries > maxEntries) {
 584                 processWarningOccurred(
 585 "tRNS chunk has more entries than prior PLTE chunk, ignoring extras.");
 586                 numEntries = maxEntries;
 587             }
 588             metadata.tRNS_alpha = new byte[numEntries];
 589             metadata.tRNS_colorType = PNG_COLOR_PALETTE;
 590             stream.read(metadata.tRNS_alpha, 0, numEntries);
 591             stream.skipBytes(chunkLength - numEntries);
 592         } else if (colorType == PNG_COLOR_GRAY) {
 593             if (chunkLength != 2) {
 594                 processWarningOccurred(
 595 "tRNS chunk for gray image must have length 2, ignoring chunk.");
 596                 stream.skipBytes(chunkLength);
 597                 return;
 598             }
 599             metadata.tRNS_gray = stream.readUnsignedShort();
 600             metadata.tRNS_colorType = PNG_COLOR_GRAY;
 601         } else if (colorType == PNG_COLOR_RGB) {
 602             if (chunkLength != 6) {
 603                 processWarningOccurred(
 604 "tRNS chunk for RGB image must have length 6, ignoring chunk.");
 605                 stream.skipBytes(chunkLength);
 606                 return;
 607             }
 608             metadata.tRNS_red = stream.readUnsignedShort();
 609             metadata.tRNS_green = stream.readUnsignedShort();
 610             metadata.tRNS_blue = stream.readUnsignedShort();
 611             metadata.tRNS_colorType = PNG_COLOR_RGB;
 612         } else {
 613             processWarningOccurred(
 614 "Gray+Alpha and RGBS images may not have a tRNS chunk, ignoring it.");
 615             return;
 616         }
 617 
 618         metadata.tRNS_present = true;
 619     }
 620 
 621     private static byte[] inflate(byte[] b) throws IOException {
 622         InputStream bais = new ByteArrayInputStream(b);
 623         InputStream iis = new InflaterInputStream(bais);
 624         ByteArrayOutputStream baos = new ByteArrayOutputStream();
 625 
 626         int c;
 627         try {
 628             while ((c = iis.read()) != -1) {
 629                 baos.write(c);
 630             }
 631         } finally {
 632             iis.close();
 633         }
 634         return baos.toByteArray();
 635     }
 636 
 637     private void parse_zTXt_chunk(int chunkLength) throws IOException {
 638         String keyword = readNullTerminatedString("ISO-8859-1", 80);
 639         metadata.zTXt_keyword.add(keyword);
 640 
 641         int method = stream.readUnsignedByte();
 642         metadata.zTXt_compressionMethod.add(new Integer(method));
 643 
 644         byte[] b = new byte[chunkLength - keyword.length() - 2];
 645         stream.readFully(b);
 646         metadata.zTXt_text.add(new String(inflate(b), "ISO-8859-1"));
 647     }
 648 
 649     private void readMetadata() throws IIOException {
 650         if (gotMetadata) {
 651             return;
 652         }
 653 
 654         readHeader();
 655 
 656         /*
 657          * Optimization: We can skip the remaining metadata if the
 658          * ignoreMetadata flag is set, and only if this is not a palette
 659          * image (in that case, we need to read the metadata to get the
 660          * tRNS chunk, which is needed for the getImageTypes() method).
 661          */
 662         int colorType = metadata.IHDR_colorType;
 663         if (ignoreMetadata && colorType != PNG_COLOR_PALETTE) {
 664             try {
 665                 while (true) {
 666                     int chunkLength = stream.readInt();
 667                     int chunkType = stream.readInt();
 668 
 669                     if (chunkType == IDAT_TYPE) {
 670                         // We've reached the image data
 671                         stream.skipBytes(-8);
 672                         imageStartPosition = stream.getStreamPosition();
 673                         break;
 674                     } else {
 675                         // Skip the chunk plus the 4 CRC bytes that follow
 676                         stream.skipBytes(chunkLength + 4);
 677                     }
 678                 }
 679             } catch (IOException e) {
 680                 throw new IIOException("Error skipping PNG metadata", e);
 681             }
 682 
 683             gotMetadata = true;
 684             return;
 685         }
 686 
 687         try {
 688             loop: while (true) {
 689                 int chunkLength = stream.readInt();
 690                 int chunkType = stream.readInt();
 691                 int chunkCRC;
 692 
 693                 // verify the chunk length
 694                 if (chunkLength < 0) {
 695                     throw new IIOException("Invalid chunk lenght " + chunkLength);
 696                 };
 697 
 698                 try {
 699                     stream.mark();
 700                     stream.seek(stream.getStreamPosition() + chunkLength);
 701                     chunkCRC = stream.readInt();
 702                     stream.reset();
 703                 } catch (IOException e) {
 704                     throw new IIOException("Invalid chunk length " + chunkLength);
 705                 }
 706 
 707                 switch (chunkType) {
 708                 case IDAT_TYPE:
 709                     // If chunk type is 'IDAT', we've reached the image data.
 710                     stream.skipBytes(-8);
 711                     imageStartPosition = stream.getStreamPosition();
 712                     break loop;
 713                 case PLTE_TYPE:
 714                     parse_PLTE_chunk(chunkLength);
 715                     break;
 716                 case bKGD_TYPE:
 717                     parse_bKGD_chunk();
 718                     break;
 719                 case cHRM_TYPE:
 720                     parse_cHRM_chunk();
 721                     break;
 722                 case gAMA_TYPE:
 723                     parse_gAMA_chunk();
 724                     break;
 725                 case hIST_TYPE:
 726                     parse_hIST_chunk(chunkLength);
 727                     break;
 728                 case iCCP_TYPE:
 729                     parse_iCCP_chunk(chunkLength);
 730                     break;
 731                 case iTXt_TYPE:
 732                     parse_iTXt_chunk(chunkLength);
 733                     break;
 734                 case pHYs_TYPE:
 735                     parse_pHYs_chunk();
 736                     break;
 737                 case sBIT_TYPE:
 738                     parse_sBIT_chunk();
 739                     break;
 740                 case sPLT_TYPE:
 741                     parse_sPLT_chunk(chunkLength);
 742                     break;
 743                 case sRGB_TYPE:
 744                     parse_sRGB_chunk();
 745                     break;
 746                 case tEXt_TYPE:
 747                     parse_tEXt_chunk(chunkLength);
 748                     break;
 749                 case tIME_TYPE:
 750                     parse_tIME_chunk();
 751                     break;
 752                 case tRNS_TYPE:
 753                     parse_tRNS_chunk(chunkLength);
 754                     break;
 755                 case zTXt_TYPE:
 756                     parse_zTXt_chunk(chunkLength);
 757                     break;
 758                 default:
 759                     // Read an unknown chunk
 760                     byte[] b = new byte[chunkLength];
 761                     stream.readFully(b);
 762 
 763                     StringBuilder chunkName = new StringBuilder(4);
 764                     chunkName.append((char)(chunkType >>> 24));
 765                     chunkName.append((char)((chunkType >> 16) & 0xff));
 766                     chunkName.append((char)((chunkType >> 8) & 0xff));
 767                     chunkName.append((char)(chunkType & 0xff));
 768 
 769                     int ancillaryBit = chunkType >>> 28;
 770                     if (ancillaryBit == 0) {
 771                         processWarningOccurred(
 772 "Encountered unknown chunk with critical bit set!");
 773                     }
 774 
 775                     metadata.unknownChunkType.add(chunkName.toString());
 776                     metadata.unknownChunkData.add(b);
 777                     break;
 778                 }
 779 
 780                 // double check whether all chunk data were consumed
 781                 if (chunkCRC != stream.readInt()) {
 782                     throw new IIOException("Failed to read a chunk of type " +
 783                             chunkType);
 784                 }
 785                 stream.flushBefore(stream.getStreamPosition());
 786             }
 787         } catch (IOException e) {
 788             throw new IIOException("Error reading PNG metadata", e);
 789         }
 790 
 791         gotMetadata = true;
 792     }
 793 
 794     // Data filtering methods
 795 
 796     private static void decodeSubFilter(byte[] curr, int coff, int count,
 797                                         int bpp) {
 798         for (int i = bpp; i < count; i++) {
 799             int val;
 800 
 801             val = curr[i + coff] & 0xff;
 802             val += curr[i + coff - bpp] & 0xff;
 803 
 804             curr[i + coff] = (byte)val;
 805         }
 806     }
 807 
 808     private static void decodeUpFilter(byte[] curr, int coff,
 809                                        byte[] prev, int poff,
 810                                        int count) {
 811         for (int i = 0; i < count; i++) {
 812             int raw = curr[i + coff] & 0xff;
 813             int prior = prev[i + poff] & 0xff;
 814 
 815             curr[i + coff] = (byte)(raw + prior);
 816         }
 817     }
 818 
 819     private static void decodeAverageFilter(byte[] curr, int coff,
 820                                             byte[] prev, int poff,
 821                                             int count, int bpp) {
 822         int raw, priorPixel, priorRow;
 823 
 824         for (int i = 0; i < bpp; i++) {
 825             raw = curr[i + coff] & 0xff;
 826             priorRow = prev[i + poff] & 0xff;
 827 
 828             curr[i + coff] = (byte)(raw + priorRow/2);
 829         }
 830 
 831         for (int i = bpp; i < count; i++) {
 832             raw = curr[i + coff] & 0xff;
 833             priorPixel = curr[i + coff - bpp] & 0xff;
 834             priorRow = prev[i + poff] & 0xff;
 835 
 836             curr[i + coff] = (byte)(raw + (priorPixel + priorRow)/2);
 837         }
 838     }
 839 
 840     private static int paethPredictor(int a, int b, int c) {
 841         int p = a + b - c;
 842         int pa = Math.abs(p - a);
 843         int pb = Math.abs(p - b);
 844         int pc = Math.abs(p - c);
 845 
 846         if ((pa <= pb) && (pa <= pc)) {
 847             return a;
 848         } else if (pb <= pc) {
 849             return b;
 850         } else {
 851             return c;
 852         }
 853     }
 854 
 855     private static void decodePaethFilter(byte[] curr, int coff,
 856                                           byte[] prev, int poff,
 857                                           int count, int bpp) {
 858         int raw, priorPixel, priorRow, priorRowPixel;
 859 
 860         for (int i = 0; i < bpp; i++) {
 861             raw = curr[i + coff] & 0xff;
 862             priorRow = prev[i + poff] & 0xff;
 863 
 864             curr[i + coff] = (byte)(raw + priorRow);
 865         }
 866 
 867         for (int i = bpp; i < count; i++) {
 868             raw = curr[i + coff] & 0xff;
 869             priorPixel = curr[i + coff - bpp] & 0xff;
 870             priorRow = prev[i + poff] & 0xff;
 871             priorRowPixel = prev[i + poff - bpp] & 0xff;
 872 
 873             curr[i + coff] = (byte)(raw + paethPredictor(priorPixel,
 874                                                          priorRow,
 875                                                          priorRowPixel));
 876         }
 877     }
 878 
 879     private static final int[][] bandOffsets = {
 880         null,
 881         { 0 }, // G
 882         { 0, 1 }, // GA in GA order
 883         { 0, 1, 2 }, // RGB in RGB order
 884         { 0, 1, 2, 3 } // RGBA in RGBA order
 885     };
 886 
 887     private WritableRaster createRaster(int width, int height, int bands,
 888                                         int scanlineStride,
 889                                         int bitDepth) {
 890 
 891         DataBuffer dataBuffer;
 892         WritableRaster ras = null;
 893         Point origin = new Point(0, 0);
 894         if ((bitDepth < 8) && (bands == 1)) {
 895             dataBuffer = new DataBufferByte(height*scanlineStride);
 896             ras = Raster.createPackedRaster(dataBuffer,
 897                                             width, height,
 898                                             bitDepth,
 899                                             origin);
 900         } else if (bitDepth <= 8) {
 901             dataBuffer = new DataBufferByte(height*scanlineStride);
 902             ras = Raster.createInterleavedRaster(dataBuffer,
 903                                                  width, height,
 904                                                  scanlineStride,
 905                                                  bands,
 906                                                  bandOffsets[bands],
 907                                                  origin);
 908         } else {
 909             dataBuffer = new DataBufferUShort(height*scanlineStride);
 910             ras = Raster.createInterleavedRaster(dataBuffer,
 911                                                  width, height,
 912                                                  scanlineStride,
 913                                                  bands,
 914                                                  bandOffsets[bands],
 915                                                  origin);
 916         }
 917 
 918         return ras;
 919     }
 920 
 921     private void skipPass(int passWidth, int passHeight)
 922         throws IOException, IIOException  {
 923         if ((passWidth == 0) || (passHeight == 0)) {
 924             return;
 925         }
 926 
 927         int inputBands = inputBandsForColorType[metadata.IHDR_colorType];
 928         int bytesPerRow = (inputBands*passWidth*metadata.IHDR_bitDepth + 7)/8;
 929 
 930         // Read the image row-by-row
 931         for (int srcY = 0; srcY < passHeight; srcY++) {
 932             // Skip filter byte and the remaining row bytes
 933             pixelStream.skipBytes(1 + bytesPerRow);
 934 
 935             // If read has been aborted, just return
 936             // processReadAborted will be called later
 937             if (abortRequested()) {
 938                 return;
 939             }
 940         }
 941     }
 942 
 943     private void updateImageProgress(int newPixels) {
 944         pixelsDone += newPixels;
 945         processImageProgress(100.0F*pixelsDone/totalPixels);
 946     }
 947 
 948     private void decodePass(int passNum,
 949                             int xStart, int yStart,
 950                             int xStep, int yStep,
 951                             int passWidth, int passHeight) throws IOException {
 952 
 953         if ((passWidth == 0) || (passHeight == 0)) {
 954             return;
 955         }
 956 
 957         WritableRaster imRas = theImage.getWritableTile(0, 0);
 958         int dstMinX = imRas.getMinX();
 959         int dstMaxX = dstMinX + imRas.getWidth() - 1;
 960         int dstMinY = imRas.getMinY();
 961         int dstMaxY = dstMinY + imRas.getHeight() - 1;
 962 
 963         // Determine which pixels will be updated in this pass
 964         int[] vals =
 965           ReaderUtil.computeUpdatedPixels(sourceRegion,
 966                                           destinationOffset,
 967                                           dstMinX, dstMinY,
 968                                           dstMaxX, dstMaxY,
 969                                           sourceXSubsampling,
 970                                           sourceYSubsampling,
 971                                           xStart, yStart,
 972                                           passWidth, passHeight,
 973                                           xStep, yStep);
 974         int updateMinX = vals[0];
 975         int updateMinY = vals[1];
 976         int updateWidth = vals[2];
 977         int updateXStep = vals[4];
 978         int updateYStep = vals[5];
 979 
 980         int bitDepth = metadata.IHDR_bitDepth;
 981         int inputBands = inputBandsForColorType[metadata.IHDR_colorType];
 982         int bytesPerPixel = (bitDepth == 16) ? 2 : 1;
 983         bytesPerPixel *= inputBands;
 984 
 985         int bytesPerRow = (inputBands*passWidth*bitDepth + 7)/8;
 986         int eltsPerRow = (bitDepth == 16) ? bytesPerRow/2 : bytesPerRow;
 987 
 988         // If no pixels need updating, just skip the input data
 989         if (updateWidth == 0) {
 990             for (int srcY = 0; srcY < passHeight; srcY++) {
 991                 // Update count of pixels read
 992                 updateImageProgress(passWidth);
 993                 // Skip filter byte and the remaining row bytes
 994                 pixelStream.skipBytes(1 + bytesPerRow);
 995             }
 996             return;
 997         }
 998 
 999         // Backwards map from destination pixels
1000         // (dstX = updateMinX + k*updateXStep)
1001         // to source pixels (sourceX), and then
1002         // to offset and skip in passRow (srcX and srcXStep)
1003         int sourceX =
1004             (updateMinX - destinationOffset.x)*sourceXSubsampling +
1005             sourceRegion.x;
1006         int srcX = (sourceX - xStart)/xStep;
1007 
1008         // Compute the step factor in the source
1009         int srcXStep = updateXStep*sourceXSubsampling/xStep;
1010 
1011         byte[] byteData = null;
1012         short[] shortData = null;
1013         byte[] curr = new byte[bytesPerRow];
1014         byte[] prior = new byte[bytesPerRow];
1015 
1016         // Create a 1-row tall Raster to hold the data
1017         WritableRaster passRow = createRaster(passWidth, 1, inputBands,
1018                                               eltsPerRow,
1019                                               bitDepth);
1020 
1021         // Create an array suitable for holding one pixel
1022         int[] ps = passRow.getPixel(0, 0, (int[])null);
1023 
1024         DataBuffer dataBuffer = passRow.getDataBuffer();
1025         int type = dataBuffer.getDataType();
1026         if (type == DataBuffer.TYPE_BYTE) {
1027             byteData = ((DataBufferByte)dataBuffer).getData();
1028         } else {
1029             shortData = ((DataBufferUShort)dataBuffer).getData();
1030         }
1031 
1032         processPassStarted(theImage,
1033                            passNum,
1034                            sourceMinProgressivePass,
1035                            sourceMaxProgressivePass,
1036                            updateMinX, updateMinY,
1037                            updateXStep, updateYStep,
1038                            destinationBands);
1039 
1040         // Handle source and destination bands
1041         if (sourceBands != null) {
1042             passRow = passRow.createWritableChild(0, 0,
1043                                                   passRow.getWidth(), 1,
1044                                                   0, 0,
1045                                                   sourceBands);
1046         }
1047         if (destinationBands != null) {
1048             imRas = imRas.createWritableChild(0, 0,
1049                                               imRas.getWidth(),
1050                                               imRas.getHeight(),
1051                                               0, 0,
1052                                               destinationBands);
1053         }
1054 
1055         // Determine if all of the relevant output bands have the
1056         // same bit depth as the source data
1057         boolean adjustBitDepths = false;
1058         int[] outputSampleSize = imRas.getSampleModel().getSampleSize();
1059         int numBands = outputSampleSize.length;
1060         for (int b = 0; b < numBands; b++) {
1061             if (outputSampleSize[b] != bitDepth) {
1062                 adjustBitDepths = true;
1063                 break;
1064             }
1065         }
1066 
1067         // If the bit depths differ, create a lookup table per band to perform
1068         // the conversion
1069         int[][] scale = null;
1070         if (adjustBitDepths) {
1071             int maxInSample = (1 << bitDepth) - 1;
1072             int halfMaxInSample = maxInSample/2;
1073             scale = new int[numBands][];
1074             for (int b = 0; b < numBands; b++) {
1075                 int maxOutSample = (1 << outputSampleSize[b]) - 1;
1076                 scale[b] = new int[maxInSample + 1];
1077                 for (int s = 0; s <= maxInSample; s++) {
1078                     scale[b][s] =
1079                         (s*maxOutSample + halfMaxInSample)/maxInSample;
1080                 }
1081             }
1082         }
1083 
1084         // Limit passRow to relevant area for the case where we
1085         // will can setRect to copy a contiguous span
1086         boolean useSetRect = srcXStep == 1 &&
1087             updateXStep == 1 &&
1088             !adjustBitDepths &&
1089             (imRas instanceof ByteInterleavedRaster);
1090 
1091         if (useSetRect) {
1092             passRow = passRow.createWritableChild(srcX, 0,
1093                                                   updateWidth, 1,
1094                                                   0, 0,
1095                                                   null);
1096         }
1097 
1098         // Decode the (sub)image row-by-row
1099         for (int srcY = 0; srcY < passHeight; srcY++) {
1100             // Update count of pixels read
1101             updateImageProgress(passWidth);
1102 
1103             // Read the filter type byte and a row of data
1104             int filter = pixelStream.read();
1105             try {
1106                 // Swap curr and prior
1107                 byte[] tmp = prior;
1108                 prior = curr;
1109                 curr = tmp;
1110 
1111                 pixelStream.readFully(curr, 0, bytesPerRow);
1112             } catch (java.util.zip.ZipException ze) {
1113                 // TODO - throw a more meaningful exception
1114                 throw ze;
1115             }
1116 
1117             switch (filter) {
1118             case PNG_FILTER_NONE:
1119                 break;
1120             case PNG_FILTER_SUB:
1121                 decodeSubFilter(curr, 0, bytesPerRow, bytesPerPixel);
1122                 break;
1123             case PNG_FILTER_UP:
1124                 decodeUpFilter(curr, 0, prior, 0, bytesPerRow);
1125                 break;
1126             case PNG_FILTER_AVERAGE:
1127                 decodeAverageFilter(curr, 0, prior, 0, bytesPerRow,
1128                                     bytesPerPixel);
1129                 break;
1130             case PNG_FILTER_PAETH:
1131                 decodePaethFilter(curr, 0, prior, 0, bytesPerRow,
1132                                   bytesPerPixel);
1133                 break;
1134             default:
1135                 throw new IIOException("Unknown row filter type (= " +
1136                                        filter + ")!");
1137             }
1138 
1139             // Copy data into passRow byte by byte
1140             if (bitDepth < 16) {
1141                 System.arraycopy(curr, 0, byteData, 0, bytesPerRow);
1142             } else {
1143                 int idx = 0;
1144                 for (int j = 0; j < eltsPerRow; j++) {
1145                     shortData[j] =
1146                         (short)((curr[idx] << 8) | (curr[idx + 1] & 0xff));
1147                     idx += 2;
1148                 }
1149             }
1150 
1151             // True Y position in source
1152             int sourceY = srcY*yStep + yStart;
1153             if ((sourceY >= sourceRegion.y) &&
1154                 (sourceY < sourceRegion.y + sourceRegion.height) &&
1155                 (((sourceY - sourceRegion.y) %
1156                   sourceYSubsampling) == 0)) {
1157 
1158                 int dstY = destinationOffset.y +
1159                     (sourceY - sourceRegion.y)/sourceYSubsampling;
1160                 if (dstY < dstMinY) {
1161                     continue;
1162                 }
1163                 if (dstY > dstMaxY) {
1164                     break;
1165                 }
1166 
1167                 if (useSetRect) {
1168                     imRas.setRect(updateMinX, dstY, passRow);
1169                 } else {
1170                     int newSrcX = srcX;
1171 
1172                     for (int dstX = updateMinX;
1173                          dstX < updateMinX + updateWidth;
1174                          dstX += updateXStep) {
1175 
1176                         passRow.getPixel(newSrcX, 0, ps);
1177                         if (adjustBitDepths) {
1178                             for (int b = 0; b < numBands; b++) {
1179                                 ps[b] = scale[b][ps[b]];
1180                             }
1181                         }
1182                         imRas.setPixel(dstX, dstY, ps);
1183                         newSrcX += srcXStep;
1184                     }
1185                 }
1186 
1187                 processImageUpdate(theImage,
1188                                    updateMinX, dstY,
1189                                    updateWidth, 1,
1190                                    updateXStep, updateYStep,
1191                                    destinationBands);
1192 
1193                 // If read has been aborted, just return
1194                 // processReadAborted will be called later
1195                 if (abortRequested()) {
1196                     return;
1197                 }
1198             }
1199         }
1200 
1201         processPassComplete(theImage);
1202     }
1203 
1204     private void decodeImage()
1205         throws IOException, IIOException  {
1206         int width = metadata.IHDR_width;
1207         int height = metadata.IHDR_height;
1208 
1209         this.pixelsDone = 0;
1210         this.totalPixels = width*height;
1211 
1212         clearAbortRequest();
1213 
1214         if (metadata.IHDR_interlaceMethod == 0) {
1215             decodePass(0, 0, 0, 1, 1, width, height);
1216         } else {
1217             for (int i = 0; i <= sourceMaxProgressivePass; i++) {
1218                 int XOffset = adam7XOffset[i];
1219                 int YOffset = adam7YOffset[i];
1220                 int XSubsampling = adam7XSubsampling[i];
1221                 int YSubsampling = adam7YSubsampling[i];
1222                 int xbump = adam7XSubsampling[i + 1] - 1;
1223                 int ybump = adam7YSubsampling[i + 1] - 1;
1224 
1225                 if (i >= sourceMinProgressivePass) {
1226                     decodePass(i,
1227                                XOffset,
1228                                YOffset,
1229                                XSubsampling,
1230                                YSubsampling,
1231                                (width + xbump)/XSubsampling,
1232                                (height + ybump)/YSubsampling);
1233                 } else {
1234                     skipPass((width + xbump)/XSubsampling,
1235                              (height + ybump)/YSubsampling);
1236                 }
1237 
1238                 // If read has been aborted, just return
1239                 // processReadAborted will be called later
1240                 if (abortRequested()) {
1241                     return;
1242                 }
1243             }
1244         }
1245     }
1246 
1247     private void readImage(ImageReadParam param) throws IIOException {
1248         readMetadata();
1249 
1250         int width = metadata.IHDR_width;
1251         int height = metadata.IHDR_height;
1252 
1253         // Init default values
1254         sourceXSubsampling = 1;
1255         sourceYSubsampling = 1;
1256         sourceMinProgressivePass = 0;
1257         sourceMaxProgressivePass = 6;
1258         sourceBands = null;
1259         destinationBands = null;
1260         destinationOffset = new Point(0, 0);
1261 
1262         // If an ImageReadParam is available, get values from it
1263         if (param != null) {
1264             sourceXSubsampling = param.getSourceXSubsampling();
1265             sourceYSubsampling = param.getSourceYSubsampling();
1266 
1267             sourceMinProgressivePass =
1268                 Math.max(param.getSourceMinProgressivePass(), 0);
1269             sourceMaxProgressivePass =
1270                 Math.min(param.getSourceMaxProgressivePass(), 6);
1271 
1272             sourceBands = param.getSourceBands();
1273             destinationBands = param.getDestinationBands();
1274             destinationOffset = param.getDestinationOffset();
1275         }
1276         Inflater inf = null;
1277         try {
1278             stream.seek(imageStartPosition);
1279 
1280             Enumeration<InputStream> e = new PNGImageDataEnumeration(stream);
1281             InputStream is = new SequenceInputStream(e);
1282 
1283            /* InflaterInputStream uses an Inflater instance which consumes
1284             * native (non-GC visible) resources. This is normally implicitly
1285             * freed when the stream is closed. However since the
1286             * InflaterInputStream wraps a client-supplied input stream,
1287             * we cannot close it.
1288             * But the app may depend on GC finalization to close the stream.
1289             * Therefore to ensure timely freeing of native resources we
1290             * explicitly create the Inflater instance and free its resources
1291             * when we are done with the InflaterInputStream by calling
1292             * inf.end();
1293             */
1294             inf = new Inflater();
1295             is = new InflaterInputStream(is, inf);
1296             is = new BufferedInputStream(is);
1297             this.pixelStream = new DataInputStream(is);
1298 
1299             /*
1300              * NB: the PNG spec declares that valid range for width
1301              * and height is [1, 2^31-1], so here we may fail to allocate
1302              * a buffer for destination image due to memory limitation.
1303              *
1304              * However, the recovery strategy for this case should be
1305              * defined on the level of application, so we will not
1306              * try to estimate the required amount of the memory and/or
1307              * handle OOM in any way.
1308              */
1309             theImage = getDestination(param,
1310                                       getImageTypes(0),
1311                                       width,
1312                                       height);
1313 
1314             Rectangle destRegion = new Rectangle(0, 0, 0, 0);
1315             sourceRegion = new Rectangle(0, 0, 0, 0);
1316             computeRegions(param, width, height,
1317                            theImage,
1318                            sourceRegion, destRegion);
1319             destinationOffset.setLocation(destRegion.getLocation());
1320 
1321             // At this point the header has been read and we know
1322             // how many bands are in the image, so perform checking
1323             // of the read param.
1324             int colorType = metadata.IHDR_colorType;
1325             checkReadParamBandSettings(param,
1326                                        inputBandsForColorType[colorType],
1327                                       theImage.getSampleModel().getNumBands());
1328 
1329             processImageStarted(0);
1330             decodeImage();
1331             if (abortRequested()) {
1332                 processReadAborted();
1333             } else {
1334                 processImageComplete();
1335             }
1336         } catch (IOException e) {
1337             throw new IIOException("Error reading PNG image data", e);
1338         } finally {
1339             if (inf != null) {
1340                 inf.end();
1341             }
1342         }
1343     }
1344 
1345     public int getNumImages(boolean allowSearch) throws IIOException {
1346         if (stream == null) {
1347             throw new IllegalStateException("No input source set!");
1348         }
1349         if (seekForwardOnly && allowSearch) {
1350             throw new IllegalStateException
1351                 ("seekForwardOnly and allowSearch can't both be true!");
1352         }
1353         return 1;
1354     }
1355 
1356     public int getWidth(int imageIndex) throws IIOException {
1357         if (imageIndex != 0) {
1358             throw new IndexOutOfBoundsException("imageIndex != 0!");
1359         }
1360 
1361         readHeader();
1362 
1363         return metadata.IHDR_width;
1364     }
1365 
1366     public int getHeight(int imageIndex) throws IIOException {
1367         if (imageIndex != 0) {
1368             throw new IndexOutOfBoundsException("imageIndex != 0!");
1369         }
1370 
1371         readHeader();
1372 
1373         return metadata.IHDR_height;
1374     }
1375 
1376     public Iterator<ImageTypeSpecifier> getImageTypes(int imageIndex)
1377       throws IIOException
1378     {
1379         if (imageIndex != 0) {
1380             throw new IndexOutOfBoundsException("imageIndex != 0!");
1381         }
1382 
1383         readHeader();
1384 
1385         ArrayList<ImageTypeSpecifier> l =
1386             new ArrayList<ImageTypeSpecifier>(1);
1387 
1388         ColorSpace rgb;
1389         ColorSpace gray;
1390         int[] bandOffsets;
1391 
1392         int bitDepth = metadata.IHDR_bitDepth;
1393         int colorType = metadata.IHDR_colorType;
1394 
1395         int dataType;
1396         if (bitDepth <= 8) {
1397             dataType = DataBuffer.TYPE_BYTE;
1398         } else {
1399             dataType = DataBuffer.TYPE_USHORT;
1400         }
1401 
1402         switch (colorType) {
1403         case PNG_COLOR_GRAY:
1404             // Packed grayscale
1405             l.add(ImageTypeSpecifier.createGrayscale(bitDepth,
1406                                                      dataType,
1407                                                      false));
1408             break;
1409 
1410         case PNG_COLOR_RGB:
1411             if (bitDepth == 8) {
1412                 // some standard types of buffered images
1413                 // which can be used as destination
1414                 l.add(ImageTypeSpecifier.createFromBufferedImageType(
1415                           BufferedImage.TYPE_3BYTE_BGR));
1416 
1417                 l.add(ImageTypeSpecifier.createFromBufferedImageType(
1418                           BufferedImage.TYPE_INT_RGB));
1419 
1420                 l.add(ImageTypeSpecifier.createFromBufferedImageType(
1421                           BufferedImage.TYPE_INT_BGR));
1422 
1423             }
1424             // Component R, G, B
1425             rgb = ColorSpace.getInstance(ColorSpace.CS_sRGB);
1426             bandOffsets = new int[3];
1427             bandOffsets[0] = 0;
1428             bandOffsets[1] = 1;
1429             bandOffsets[2] = 2;
1430             l.add(ImageTypeSpecifier.createInterleaved(rgb,
1431                                                        bandOffsets,
1432                                                        dataType,
1433                                                        false,
1434                                                        false));
1435             break;
1436 
1437         case PNG_COLOR_PALETTE:
1438             readMetadata(); // Need tRNS chunk
1439 
1440             /*
1441              * The PLTE chunk spec says:
1442              *
1443              * The number of palette entries must not exceed the range that
1444              * can be represented in the image bit depth (for example, 2^4 = 16
1445              * for a bit depth of 4). It is permissible to have fewer entries
1446              * than the bit depth would allow. In that case, any out-of-range
1447              * pixel value found in the image data is an error.
1448              *
1449              * http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html#C.PLTE
1450              *
1451              * Consequently, the case when the palette length is smaller than
1452              * 2^bitDepth is legal in the view of PNG spec.
1453              *
1454              * However the spec of createIndexed() method demands the exact
1455              * equality of the palette lengh and number of possible palette
1456              * entries (2^bitDepth).
1457              *
1458              * {@link javax.imageio.ImageTypeSpecifier.html#createIndexed}
1459              *
1460              * In order to avoid this contradiction we need to extend the
1461              * palette arrays to the limit defined by the bitDepth.
1462              */
1463 
1464             int plength = 1 << bitDepth;
1465 
1466             byte[] red = metadata.PLTE_red;
1467             byte[] green = metadata.PLTE_green;
1468             byte[] blue = metadata.PLTE_blue;
1469 
1470             if (metadata.PLTE_red.length < plength) {
1471                 red = Arrays.copyOf(metadata.PLTE_red, plength);
1472                 Arrays.fill(red, metadata.PLTE_red.length, plength,
1473                             metadata.PLTE_red[metadata.PLTE_red.length - 1]);
1474 
1475                 green = Arrays.copyOf(metadata.PLTE_green, plength);
1476                 Arrays.fill(green, metadata.PLTE_green.length, plength,
1477                             metadata.PLTE_green[metadata.PLTE_green.length - 1]);
1478 
1479                 blue = Arrays.copyOf(metadata.PLTE_blue, plength);
1480                 Arrays.fill(blue, metadata.PLTE_blue.length, plength,
1481                             metadata.PLTE_blue[metadata.PLTE_blue.length - 1]);
1482 
1483             }
1484 
1485             // Alpha from tRNS chunk may have fewer entries than
1486             // the RGB LUTs from the PLTE chunk; if so, pad with
1487             // 255.
1488             byte[] alpha = null;
1489             if (metadata.tRNS_present && (metadata.tRNS_alpha != null)) {
1490                 if (metadata.tRNS_alpha.length == red.length) {
1491                     alpha = metadata.tRNS_alpha;
1492                 } else {
1493                     alpha = Arrays.copyOf(metadata.tRNS_alpha, red.length);
1494                     Arrays.fill(alpha,
1495                                 metadata.tRNS_alpha.length,
1496                                 red.length, (byte)255);
1497                 }
1498             }
1499 
1500             l.add(ImageTypeSpecifier.createIndexed(red, green,
1501                                                    blue, alpha,
1502                                                    bitDepth,
1503                                                    DataBuffer.TYPE_BYTE));
1504             break;
1505 
1506         case PNG_COLOR_GRAY_ALPHA:
1507             // Component G, A
1508             gray = ColorSpace.getInstance(ColorSpace.CS_GRAY);
1509             bandOffsets = new int[2];
1510             bandOffsets[0] = 0;
1511             bandOffsets[1] = 1;
1512             l.add(ImageTypeSpecifier.createInterleaved(gray,
1513                                                        bandOffsets,
1514                                                        dataType,
1515                                                        true,
1516                                                        false));
1517             break;
1518 
1519         case PNG_COLOR_RGB_ALPHA:
1520             if (bitDepth == 8) {
1521                 // some standard types of buffered images
1522                 // wich can be used as destination
1523                 l.add(ImageTypeSpecifier.createFromBufferedImageType(
1524                           BufferedImage.TYPE_4BYTE_ABGR));
1525 
1526                 l.add(ImageTypeSpecifier.createFromBufferedImageType(
1527                           BufferedImage.TYPE_INT_ARGB));
1528             }
1529 
1530             // Component R, G, B, A (non-premultiplied)
1531             rgb = ColorSpace.getInstance(ColorSpace.CS_sRGB);
1532             bandOffsets = new int[4];
1533             bandOffsets[0] = 0;
1534             bandOffsets[1] = 1;
1535             bandOffsets[2] = 2;
1536             bandOffsets[3] = 3;
1537 
1538             l.add(ImageTypeSpecifier.createInterleaved(rgb,
1539                                                        bandOffsets,
1540                                                        dataType,
1541                                                        true,
1542                                                        false));
1543             break;
1544 
1545         default:
1546             break;
1547         }
1548 
1549         return l.iterator();
1550     }
1551 
1552     /*
1553      * Super class implementation uses first element
1554      * of image types list as raw image type.
1555      *
1556      * Also, super implementation uses first element of this list
1557      * as default destination type image read param does not specify
1558      * anything other.
1559      *
1560      * However, in case of RGB and RGBA color types, raw image type
1561      * produces buffered image of custom type. It causes some
1562      * performance degradation of subsequent rendering operations.
1563      *
1564      * To resolve this contradiction we put standard image types
1565      * at the first positions of image types list (to produce standard
1566      * images by default) and put raw image type (which is custom)
1567      * at the last position of this list.
1568      *
1569      * After this changes we should override getRawImageType()
1570      * to return last element of image types list.
1571      */
1572     public ImageTypeSpecifier getRawImageType(int imageIndex)
1573       throws IOException {
1574 
1575         Iterator<ImageTypeSpecifier> types = getImageTypes(imageIndex);
1576         ImageTypeSpecifier raw = null;
1577         do {
1578             raw = types.next();
1579         } while (types.hasNext());
1580         return raw;
1581     }
1582 
1583     public ImageReadParam getDefaultReadParam() {
1584         return new ImageReadParam();
1585     }
1586 
1587     public IIOMetadata getStreamMetadata()
1588         throws IIOException {
1589         return null;
1590     }
1591 
1592     public IIOMetadata getImageMetadata(int imageIndex) throws IIOException {
1593         if (imageIndex != 0) {
1594             throw new IndexOutOfBoundsException("imageIndex != 0!");
1595         }
1596         readMetadata();
1597         return metadata;
1598     }
1599 
1600     public BufferedImage read(int imageIndex, ImageReadParam param)
1601         throws IIOException {
1602         if (imageIndex != 0) {
1603             throw new IndexOutOfBoundsException("imageIndex != 0!");
1604         }
1605 
1606         readImage(param);
1607         return theImage;
1608     }
1609 
1610     public void reset() {
1611         super.reset();
1612         resetStreamSettings();
1613     }
1614 
1615     private void resetStreamSettings() {
1616         gotHeader = false;
1617         gotMetadata = false;
1618         metadata = null;
1619         pixelStream = null;
1620     }
1621 }