Class PngImage
- java.lang.Object
-
- com.sixlegs.png.PngImage
-
- All Implemented Interfaces:
java.awt.Transparency
public class PngImage extends java.lang.Object implements java.awt.TransparencyA class to decode PNG images. The simplest use is if only a decodedBufferedImageis required:BufferedImage image = new PngImage().read(new java.io.File("test.png"));ThePngImageinstance used to read the image also stores all of the image metadata. For customized PNG decoding, aPngConfigobject may be passed to the constructor.This class is not thread-safe. Do not share a
PngImageinstance among multiple threads without proper synchronization.For more information visit http://www.sixlegs.com/
- Author:
- Chris Nokleberg <chris@sixlegs.com>
- See Also:
PngConfig
-
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description protected java.awt.image.BufferedImagecreateImage(java.io.InputStream in, java.awt.Dimension size)A hook by which subclasses can access or manipulate the raw image data.java.awt.ColorgetBackground()Returns the background color explicitly encoded in the image.intgetBitDepth()Returns the image bit depth.intgetColorType()Returns the image color type.PngConfiggetConfig()Returns the configuration used by this object.floatgetGamma()Returns the gamma exponent that was explicitly encoded in the image, if there was one, or the value ofPngConfig.getDefaultGamma()otherwise.short[]getGammaTable()Returns a gamma table which can be used for custom gamma correction.intgetHeight()Returns the image height in pixels.java.util.MapgetProperties()Returns the map which stores all of this image's property values.java.lang.ObjectgetProperty(java.lang.String name)Returns a per-image property by name.intgetSamples()Returns the number of samples per pixel.TextChunkgetTextChunk(java.lang.String key)Returns a text chunk that uses the given keyword, if one exists.intgetTransparency()Returns the type of this Transparency.intgetWidth()Returns the image widt hin pixels.protected booleanhandlePass(java.awt.image.BufferedImage image, int pass)A method which subclasses may override to take some action after each pass has been decoded.protected booleanhandleProgress(java.awt.image.BufferedImage image, float pct)Reports the approximate degree of completion of the current read call.protected voidhandleWarning(PngException e)Callback for customized handling of warnings.booleanisInterlaced()Returns true if the image interlace type (PngConstants.INTERLACE) is something other thanINTERLACE_NONE.protected booleanisMultipleOK(int type)Returns whether a chunk is allowed to occur multiple times.java.awt.image.BufferedImageread(java.io.File file)Reads a PNG image from the specified file.java.awt.image.BufferedImageread(java.io.InputStream in, boolean close)Reads a PNG image from the specified input stream.protected voidreadChunk(int type, java.io.DataInput in, long offset, int length)Read the chunk data from the image input stream, storing properties into thisPngImageinstance.
-
-
-
Method Detail
-
getConfig
public PngConfig getConfig()
Returns the configuration used by this object.- Returns:
- the
PngConfiginstance used by this object
-
read
public java.awt.image.BufferedImage read(java.io.File file) throws java.io.IOExceptionReads a PNG image from the specified file. Image metadata will be stored in the property map of thisPngImageinstance, for retrieval via the various helper methods (getWidth(),getHeight(), etc.) andgetProperty(java.lang.String). The decoded image itself is returned by this method but not cached.If
PngConfig.getReadLimit()is anything butPngConfig.READ_ALL, then this method will return null instead of the decoded image.Multiple images can be read using the same
PngImageinstance. The property map is cleared each time this method is called.- Parameters:
file- the file to read- Returns:
- the decoded image, or null if no image was decoded
- Throws:
java.io.IOException- if any error occurred while reading the image- See Also:
read(java.io.InputStream, boolean),createImage(java.io.InputStream, java.awt.Dimension),handlePass(java.awt.image.BufferedImage, int)
-
read
public java.awt.image.BufferedImage read(java.io.InputStream in, boolean close) throws java.io.IOExceptionReads a PNG image from the specified input stream. Image metadata will be stored in the property map of thisPngImageinstance, for retrieval via the various helper methods (getWidth(),getHeight(), etc.) andgetProperty(java.lang.String). The decoded image itself is returned by this method but not cached.If
PngConfig.getReadLimit()is anything butPngConfig.READ_ALL, then this method will return null instead of the decoded image.Multiple images can be read using the same
PngImageinstance. A new property map is created each time this method is called.- Parameters:
in- the input stream to readclose- whether to close the input stream after reading- Returns:
- the decoded image, or null if no image was decoded
- Throws:
java.io.IOException- if any error occurred while reading the image- See Also:
read(java.io.File),createImage(java.io.InputStream, java.awt.Dimension),handlePass(java.awt.image.BufferedImage, int)
-
createImage
protected java.awt.image.BufferedImage createImage(java.io.InputStream in, java.awt.Dimension size) throws java.io.IOExceptionA hook by which subclasses can access or manipulate the raw image data. All of the raw, compressed image data contained in theIDATchunks of the PNG image being read is concatenated and passed to this method as a single input stream. The returned image will become the return value of the callingread(java.io.File)orread(java.io.InputStream, boolean)method.Unlike
readChunk(int, java.io.DataInput, long, int)implementations, subclasses may read less than the correct amount from this stream; the remainder will be skipped.- Parameters:
in- the input stream of raw, compressed image datasize- the size of the image data- Returns:
- the decoded image, or null
- Throws:
java.io.IOException- if any error occurred while processing the image data
-
handlePass
protected boolean handlePass(java.awt.image.BufferedImage image, int pass)A method which subclasses may override to take some action after each pass has been decoded. An interlaced image has seven passes, and non-interlaced image only one. Thepassarguments indicates the index of the completed pass, starting with zero.For interlaced images, the state of the image data before the last pass is affected by the value of
PngConfig.getProgressive().Image decoding can be aborted by returning false. The default implementation always returns true.
- Parameters:
image- the partially or fully decoded imagepass- the index of the completed pass- Returns:
- false to abort image decoding
-
handleProgress
protected boolean handleProgress(java.awt.image.BufferedImage image, float pct)Reports the approximate degree of completion of the current read call. This method is called periodically during image decoding. The degree of completion is expressed as a percentage varying from 0.0F to 100.0F, and is calculated using the number of pixels decoded.Image decoding can be aborted by returning false. The default implementation returns true.
- Parameters:
image- the partially or fully decoded imagepct- the approximate percentage of decoding that has been completed- Returns:
- false to abort image decoding
-
handleWarning
protected void handleWarning(PngException e) throws PngException
Callback for customized handling of warnings. Whenever a non-fatal error is found, an instance ofPngExceptionis created and passed to this method. To signal that the exception should be treated as a fatal exception (and abort image processing), an implementation should re-throw the exception.By default, this method will re-throw the warning if the
warningsFatalproperty is true.- Throws:
PngException- if the warning should be treated as fatal
-
getWidth
public int getWidth()
Returns the image widt hin pixels.- Throws:
java.lang.IllegalStateException- if an image has not been read
-
getHeight
public int getHeight()
Returns the image height in pixels.- Throws:
java.lang.IllegalStateException- if an image has not been read
-
getBitDepth
public int getBitDepth()
Returns the image bit depth.- Returns:
- 1, 2, 4, 8, or 16
- Throws:
java.lang.IllegalStateException- if an image has not been read
-
isInterlaced
public boolean isInterlaced()
Returns true if the image interlace type (PngConstants.INTERLACE) is something other thanINTERLACE_NONE.- Returns:
- true if the image is interlaced
- Throws:
java.lang.IllegalStateException- if an image has not been read
-
getColorType
public int getColorType()
Returns the image color type.- Returns:
COLOR_TYPE_GRAY,
COLOR_TYPE_GRAY_ALPHA,
COLOR_TYPE_PALETTE,
COLOR_TYPE_RGB,
orCOLOR_TYPE_RGB_ALPHA- Throws:
java.lang.IllegalStateException- if an image has not been read
-
getTransparency
public int getTransparency()
Returns the type of this Transparency.- Specified by:
getTransparencyin interfacejava.awt.Transparency- Returns:
- the field type of this Transparency, which is either OPAQUE, BITMASK or TRANSLUCENT.
- Throws:
java.lang.IllegalStateException- if an image has not been read
-
getSamples
public int getSamples()
Returns the number of samples per pixel. Gray and paletted images use one sample, gray+alpha uses two, RGB uses three, and RGB+alpha uses four.- Returns:
- 1, 2, 3 or 4
- Throws:
java.lang.IllegalStateException- if an image has not been read
-
getGamma
public float getGamma()
Returns the gamma exponent that was explicitly encoded in the image, if there was one, or the value ofPngConfig.getDefaultGamma()otherwise.- Returns:
- the gamma exponent
- Throws:
java.lang.IllegalStateException- if an image has not been read
-
getGammaTable
public short[] getGammaTable()
Returns a gamma table which can be used for custom gamma correction. The table is 256 entries unless the bit depth is 16 andPngConfig.getReduce16()is false, in which case the table is 65535 entries.The values in the table take into account
getGamma()andPngConfig.getDisplayExponent().- Returns:
- a table of component values to be used in gamma correction
- Throws:
java.lang.IllegalStateException- if an image has not been read
-
getBackground
public java.awt.Color getBackground()
Returns the background color explicitly encoded in the image. For 16-bit images the components are reduced to 8-bit by shifting.- Returns:
- the background color, or null
- Throws:
java.lang.IllegalStateException- if an image has not been read
-
getProperty
public java.lang.Object getProperty(java.lang.String name)
Returns a per-image property by name. All common property names are defined inPngConstants; their types are listed in the following table. The use of the various helper methods defined in this class, such asgetBackground(), is normally preferrable to working with the raw property values.Property Type Description BIT_DEPTHIntegerBit depth COLOR_TYPEIntegerColor type COMPRESSIONIntegerCompression method FILTERIntegerFilter method GAMMAFloatGamma WIDTHIntegerWidth HEIGHTIntegerHeight INTERLACEIntegerInterlace method PALETTEbyte[]Palette entries PALETTE_ALPHAbyte[]Palette alpha TRANSPARENCYint[]Transparency samples BACKGROUNDint[]Background samples PIXELS_PER_UNIT_XIntegerPixels per unit, X axis PIXELS_PER_UNIT_YIntegerPixels per unit, Y axis UNITIntegerUnit specifier RENDERING_INTENTIntegerRendering intent SIGNIFICANT_BITSbyte[]Significant bits TEXT_CHUNKSListList of text chunks TIMEDateImage last-modification time CHROMATICITYfloat[]Chromaticity ICC_PROFILEbyte[]ICC profile ICC_PROFILE_NAMEStringICC profile name HISTOGRAMint[]Palette histogram SUGGESTED_PALETTESListList of suggested palettes GIF_DISPOSAL_METHODIntegerGIF disposal method GIF_USER_INPUT_FLAGIntegerGIF user input flag GIF_DELAY_TIMEIntegerGIF delay time (hundredths of a second) SCALE_UNITIntegerUnit for physical scale of image subject PIXEL_WIDTHDoublePhysical width of pixel PIXEL_HEIGHTDoublePhysical height of pixel POSITION_UNITIntegerUnit for image offset STEREO_MODEIntegerIndicator of stereo image - Parameters:
name- a property name- Returns:
- the property value, or null if no such property exists
- Throws:
java.lang.IllegalStateException- if an image has not been read
-
getProperties
public java.util.Map getProperties()
Returns the map which stores all of this image's property values. The map is mutable, and storing a value with the wrong type may result in other methods in this class throwingIllegalStateExceptionorClassCastException.- Returns:
- the mutable map of image properties
-
getTextChunk
public TextChunk getTextChunk(java.lang.String key)
Returns a text chunk that uses the given keyword, if one exists. If multiple text chunks share the same keyword, this method will return the first one that was read. The full list of text chunks may be accessed by callinggetProperty(PngConstants.TEXT_CHUNKS)
- Parameters:
key- the text chunk keyword- Returns:
- a
TextChunkimplementation, or null - Throws:
java.lang.IllegalStateException- if an image has not been read
-
readChunk
protected void readChunk(int type, java.io.DataInput in, long offset, int length) throws java.io.IOExceptionRead the chunk data from the image input stream, storing properties into thisPngImageinstance.By default this method will handle all of the chunk types defined in Version 1.2 of the PNG Specification, and most of the registered extension chunks.
IDATchunks will be processed through this method only ifPngConfig.getReadLimit()is set toPngConfig.READ_EXCEPT_DATA.Attempting to read past the end of the chunk data will result in an
EOFException. Unread data will be skipped.- Parameters:
type- the chunk typein- the chunk dataoffset- the location of the chunk data within the entire PNG datastreamlength- the length of the chunk data- Throws:
java.io.IOException
-
-