signature[3] != (byte)71 ||
signature[4] != (byte)13 ||
signature[5] != (byte)10 ||
signature[6] != (byte)26 ||
signature[7] != (byte)10) {
throw new IIOException("Bad PNG signature!");
}
int IHDR_length = stream.readInt();
if (IHDR_length != 13) {
throw new IIOException("Bad length for IHDR chunk!");
}
int IHDR_type = stream.readInt();
if (IHDR_type != IHDR_TYPE) {
throw new IIOException("Bad type for IHDR chunk!");
}
this.metadata = new PNGMetadata();
int width = stream.readInt();
int height = stream.readInt();
// Re-use signature array to bulk-read these unsigned byte values
stream.readFully(signature, 0, 5);
int bitDepth = signature[0] & 0xff;
int colorType = signature[1] & 0xff;
int compressionMethod = signature[2] & 0xff;
int filterMethod = signature[3] & 0xff;
int interlaceMethod = signature[4] & 0xff;
// Skip IHDR CRC
stream.skipBytes(4);
stream.flushBefore(stream.getStreamPosition());
if (width == 0) {
throw new IIOException("Image width == 0!");
}
if (height == 0) {
throw new IIOException("Image height == 0!");
}
if (bitDepth != 1 && bitDepth != 2 && bitDepth != 4 &&
bitDepth != 8 && bitDepth != 16) {
throw new IIOException("Bit depth must be 1, 2, 4, 8, or 16!");
}
if (colorType != 0 && colorType != 2 && colorType != 3 &&
colorType != 4 && colorType != 6) {
throw new IIOException("Color type must be 0, 2, 3, 4, or 6!");
}
if (colorType == PNG_COLOR_PALETTE && bitDepth == 16) {
throw new IIOException("Bad color type/bit depth combination!");
}
if ((colorType == PNG_COLOR_RGB ||
colorType == PNG_COLOR_RGB_ALPHA ||
colorType == PNG_COLOR_GRAY_ALPHA) &&
(bitDepth != 8 && bitDepth != 16)) {
throw new IIOException("Bad color type/bit depth combination!");
}
if (compressionMethod != 0) {
throw new IIOException("Unknown compression method (not 0)!");
}
if (filterMethod != 0) {
throw new IIOException("Unknown filter method (not 0)!");
}
if (interlaceMethod != 0 && interlaceMethod != 1) {
throw new IIOException("Unknown interlace method (not 0 or 1)!");
}
metadata.IHDR_present = true;
metadata.IHDR_width = width;
metadata.IHDR_height = height;
metadata.IHDR_bitDepth = bitDepth;
metadata.IHDR_colorType = colorType;
metadata.IHDR_compressionMethod = compressionMethod;
metadata.IHDR_filterMethod = filterMethod;
metadata.IHDR_interlaceMethod = interlaceMethod;
gotHeader = true;
} catch (IOException e) {
throw new IIOException("I/O error reading PNG header!", e);
}
}