Documentation
¶
Index ¶
- Constants
- func Encode(img image.Image, w io.Writer, extra ...RawChunk) (int64, error)
- func ISO_3309_CRC32(b []byte) uint32
- type BKGD
- type CHRM
- type ChunkName
- type ChunkParse
- type EXIF
- type Encoder
- type ExifEntry
- type FilterStrategy
- type GAMA
- type HIST
- type ICCP
- type IDAT
- type IEND
- type IHDR
- type ITXT
- type PHYS
- type PLTE
- type PLTEColor
- type Png
- func (p *Png) AddRawChunk(name ChunkName, data []byte) error
- func (p *Png) DeleteRawChunk(name ChunkName) int
- func (p *Png) GetOtherChunkByName(name ChunkName) ([]ChunkParse, error)
- func (p *Png) IDATsToColor() (image.Image, error)
- func (p *Png) MarshalBytes() ([]byte, error)
- func (p *Png) ParseChunk(c ChunkParse, notSave ...bool) error
- func (p *Png) RawChunkByName(name ChunkName) ([]byte, bool)
- func (p *Png) RawChunks() []RawChunk
- func (p *Png) ReplaceImage(img image.Image) error
- func (p *Png) WriteTo(w io.Writer) (int64, error)
- type RawChunk
- type SBIT
- type SRGB
- type TEXT
- type TIME
- type TRNS
- type ZTXT
Constants ¶
const CompressionDefault = 0
CompressionDefault is the zero value of Encoder.CompressionLevel and means the zlib default compression level (6).
const CompressionNone = -2
CompressionNone switches the zlib compressor to "huffman only" mode: still lossless, the fastest level, but with the biggest output size.
Variables ¶
This section is empty.
Functions ¶
func Encode ¶ added in v1.1.0
Encode encodes img as a png stream with default encoder settings (filter heuristic and default zlib compression), see Encoder for the details.
func ISO_3309_CRC32 ¶ added in v1.1.0
ISO_3309_CRC32 computes the 32-bit CRC defined in ISO 3309 (ITU-T V.42) and required by the PNG specification for every chunk. It is the same polynomial as IEEE 802.3 / zlib's crc32: x32+x26+x23+x22+x16+x12+x11+x10+x8+x7+x5+x4+x2+x+1
Types ¶
type BKGD ¶
type BKGD struct {
// For color type 3 (indexed color): the palette index of the background color.
Palette uint8
// For color types 0 and 4 (grayscale): the gray level of the background color.
Gray uint16
// For color types 2 and 6 (truecolor): the rgb color of the background.
Red uint16
Green uint16
Blue uint16
}
BKGD The bKGD chunk specifies a default background color to present the image against. Note that viewers are not bound to honor this chunk; a viewer can choose to use a different background. For color type 3 (indexed color), the bKGD chunk contains:
Palette index: 1 byte
The value is the palette index of the color to be used as background. For color types 0 and 4 (grayscale, with or without alpha), bKGD contains:
Gray: 2 bytes, range 0 .. (2^bitdepth)-1
(For consistency, 2 bytes are used regardless of the image bit depth.) The value is the gray level to be used as background. For color types 2 and 6 (truecolor, with or without alpha), bKGD contains:
Red: 2 bytes, range 0 .. (2^bitdepth)-1 Green: 2 bytes, range 0 .. (2^bitdepth)-1 Blue: 2 bytes, range 0 .. (2^bitdepth)-1
(For consistency, 2 bytes per sample are used regardless of the image bit depth.) This is the RGB color to be used as background. When present, the bKGD chunk must precede the first IDAT chunk, and must follow the PLTE chunk, if any.
See Recommendations for Decoders: Background color.
type CHRM ¶
type CHRM struct {
WhiteX uint32
WhiteY uint32
RedX uint32
RedY uint32
GreenX uint32
GreenY uint32
BlueX uint32
BlueY uint32
}
CHRM Applications that need device-independent specification of colors in a PNG file can use the cHRM chunk to specify the 1931 CIE x,y chromaticities of the red, green, and blue primaries used in the image, and the referenced white point. See Color Tutorial for more information. The cHRM chunk contains:
White Point x: 4 bytes White Point y: 4 bytes Red x: 4 bytes Red y: 4 bytes Green x: 4 bytes Green y: 4 bytes Blue x: 4 bytes Blue y: 4 bytes
Each value is encoded as a 4-byte unsigned integer, representing the x or y value times 100000. For example, a value of 0.3127 would be stored as the integer 31270. cHRM is allowed in all PNG files, although it is of little value for grayscale images.
If the encoder does not know the chromaticity values, it should not write a cHRM chunk; the absence of a cHRM chunk indicates that the image's primary colors are device-dependent.
If the cHRM chunk appears, it must precede the first IDAT chunk, and it must also precede the PLTE chunk if present.
See Recommendations for Encoders: Encoder color handling, and Recommendations for Decoders: Decoder color handling.
type ChunkName ¶
type ChunkName string
const ( IHDRChunk ChunkName = "IHDR" PLTEChunk ChunkName = "PLTE" IDATChunk ChunkName = "IDAT" IENDChunk ChunkName = "IEND" BKGDChunk ChunkName = "bKGD" CHRMChunk ChunkName = "cHRM" GAMAChunk ChunkName = "gAMA" HISTChunk ChunkName = "hIST" SBITChunk ChunkName = "sBIT" TRNSChunk ChunkName = "tRNS" PHYSChunk ChunkName = "pHYs" TEXTChunk ChunkName = "tEXt" ZTXTChunk ChunkName = "zTXt" ITXTChunk ChunkName = "iTXt" TIMEChunk ChunkName = "tIME" SRGBChunk ChunkName = "sRGB" ICCPChunk ChunkName = "iCCP" EXIFChunk ChunkName = "eXIf" )
func NewITXTChunk ¶ added in v1.1.0
func NewITXTChunk(keyword, languageTag, translatedKeyword, text string, compress bool) (ChunkName, []byte, error)
NewITXTChunk builds the data area of a new iTXt chunk, e.g. for embedding XMP metadata (keyword "XML:com.adobe.xmp") into an already parsed file through AddRawChunk. Its result is meant to be used as the args of AddRawChunk:
name, data, err := NewITXTChunk("XML:com.adobe.xmp", "", "", xmp, true)
p.AddRawChunk(name, data)
The keyword must be 1-79 bytes long and none of the values may contain a null byte.
type ChunkParse ¶
ChunkParse is the interface of every chunk type the library parses natively and of any custom chunk type a caller provides: implement ChunkName (the 4 byte type code to look up) and Parse (which receives the raw chunk as name + data + crc and fills the receiver's fields).
type EXIF ¶ added in v1.1.0
type EXIF struct {
// Data is the TIFF stream of the chunk without the chunk type fields.
Data []byte
}
EXIF The eXIf chunk holds EXIF metadata: an Exchangeable Image File Format (TIFF) structure, byte order II (little-endian) or MM (big-endian), with one or more image file directories (IFD).
Multiple eXIf chunks are allowed by the spec; the library parses the FIRST one into the EXIF struct while the others stay raw (see RawChunks).
The TIFF blob is kept as-is: the chunk is re-produced byte for byte unless the Data field was modified. Use Entries for the structured read-only view over the file directory (the IFD0 and the Exif and GPS sub-IFDs are flattened).
type Encoder ¶ added in v1.1.0
type Encoder struct {
// CompressionLevel is a zlib level: CompressionNone (-2), 1-9, or the
// zero value CompressionDefault (0) for the default compression.
CompressionLevel int
// FilterStrategy selects the scanline filter heuristic, see the
// FilterStrategy constants. FilterHeuristic costs about 4 extra passes
// over the scanlines.
FilterStrategy FilterStrategy
// ChunkSize limits the size of every IDAT chunk in bytes; 0 (the zero
// value) produces one single IDAT chunk.
ChunkSize int
// Interlace writes the scanlines as seven Adam7 interlacing passes
// (progressive rendering on every decoder), default is non-interlaced.
Interlace bool
}
Encoder encodes standard library images as png streams. The pixel data of *image.Gray, *image.Gray16, *image.NRGBA, *image.NRGBA64 and *image.Paletted images is written directly from their Pix buffers; every other image.Image (premultiplied ones like *image.RGBA, *image.CMYK, sub-images...) is converted to 8 bit straight alpha RGB first.
With Interlace the images are written as Adam7 interlaced streams.
func (*Encoder) Encode ¶ added in v1.1.0
Encode encodes img as a png stream into w and returns the number of bytes written and an error. The extra arguments define ancillary chunks written after IHDR (and after the internal PLTE/tRNS of a palette image) and before the first IDAT chunk, e.g. XMP metadata built with NewITXTChunk or a raw pHYs chunk. Their CRC field is ignored, it is recomputed while writing. IHDR, IDAT, IEND, PLTE and tRNS cannot be passed as an extra chunk (PLTE/tRNS would collide with the ones of a palette image, use the chunks of an already parsed file through ReplaceImage instead).
type ExifEntry ¶ added in v1.1.0
ExifEntry is one entry of an exIf IFD image directory entry, with the raw bytes of its value (already resolved through the offset when the value does not fit into the entry itself).
type FilterStrategy ¶ added in v1.1.0
type FilterStrategy uint8
FilterStrategy selects how scanline filters are chosen while encoding.
const ( // FilterHeuristic picks the cheapest of the five png filter types per // scanline with the classic "minimum sum of absolute differences" // heuristic (the "adaptive filtering" recommendation of the spec). This // is the zero value: it normally gives the best compression. FilterHeuristic FilterStrategy = iota // FilterNone writes every scanline unfiltered (filter type 0 only), // which is the fastest to encode but compresses worst. FilterNone )
type GAMA ¶
type GAMA struct {
ImageGamma uint32
}
GAMA The gAMA chunk specifies the gamma of the camera (or simulated camera) that produced the image, and thus the gamma of the image with respect to the original scene. More precisely, the gAMA chunk encodes the file_gamma value, as defined in Gamma Tutorial. The gAMA chunk contains:
Image gamma: 4 bytes
The value is encoded as a 4-byte unsigned integer, representing gamma times 100000. For example, a gamma of 0.45 would be stored as the integer 45000. If the encoder does not know the image's gamma value, it should not write a gAMA chunk; the absence of a gAMA chunk indicates that the gamma is unknown.
If the gAMA chunk appears, it must precede the first IDAT chunk, and it must also precede the PLTE chunk if present.
See Gamma correction, Recommendations for Encoders: Encoder gamma handling, and Recommendations for Decoders: Decoder gamma handling.
type HIST ¶
type HIST struct {
Elements []uint16
}
HIST The hIST chunk gives the approximate usage frequency of each color in the color palette. A histogram chunk can appear only when a palette chunk appears. If a viewer is unable to provide all the colors listed in the palette, the histogram may help it decide how to choose a subset of the colors for display. The hIST chunk contains a series of 2-byte (16 bit) unsigned integers. There must be exactly one entry for each entry in the PLTE chunk. Each entry is proportional to the fraction of pixels in the image that have that palette index; the exact scale factor is chosen by the encoder.
Histogram entries are approximate, with the exception that a zero entry specifies that the corresponding palette entry is not used at all in the image. It is required that a histogram entry be nonzero if there are any pixels of that color.
When the palette is a suggested quantization of a truecolor image, the histogram is necessarily approximate, since a decoder may map pixels to palette entries differently than the encoder did. In this situation, zero entries should not appear.
The hIST chunk, if it appears, must follow the PLTE chunk, and must precede the first IDAT chunk.
See Rationale: Palette histograms, and Recommendations for Decoders: Suggested-palette and histogram usage.
type ICCP ¶ added in v1.1.0
type ICCP struct {
// Name is the Latin-1 profile name, e.g. "ICC profile".
Name string
// CompressionMethod is the compression of the profile as stored, only
// the value 0 (zlib/deflate) is defined in the spec.
CompressionMethod uint8
// Profile is the decompressed ICC profile bytes; modify this field to
// replace the profile, the chunk is re-compressed while writing.
Profile []byte
}
ICCP The iCCP chunk embeds an ICC profile. It contains:
Profile name: 1-79 bytes (Latin-1) followed by a null separator Compression method: 1 byte (only 0 = zlib/deflate is defined) Compressed profile: n bytes, a zlib datastream with the profile
A PNG datastream shall contain no more than one iCCP chunk. On the write side the chunk is reproduced byte for byte unless the Profile field was modified (or the profile name or the compression method changed), in which case the new profile is compressed again before writing.
The profile itself is parsed left as ICC bytes, use Profile.
type IDAT ¶
IDAT The IDAT chunk contains the actual image data. To create this data: Begin with image scanlines represented as described in Image layout; the layout and total size of this raw data are determined by the fields of IHDR. Filter the image data according to the filtering method specified by the IHDR chunk. (Note that with filter method 0, the only one currently defined, this implies prepending a filter type byte to each scanline.) Compress the filtered data using the compression method specified by the IHDR chunk. The IDAT chunk contains the output datastream of the compression algorithm. To read the image data, reverse this process.
There can be multiple IDAT chunks; if so, they must appear consecutively with no other intervening chunks. The compressed datastream is then the concatenation of the contents of all the IDAT chunks. The encoder can divide the compressed datastream into IDAT chunks however it wishes. (Multiple IDAT chunks are allowed so that encoders can work in a fixed amount of memory; typically the chunk size will correspond to the encoder's buffer size.) It is important to emphasize that IDAT chunk boundaries have no semantic significance and can occur at any point in the compressed datastream. A PNG file in which each IDAT chunk contains only one data byte is legal, though remarkably wasteful of space. (For that matter, zero-length IDAT chunks are legal, though even more wasteful.)
See Filter Algorithms and Deflate/Inflate Compression for details.
type IEND ¶
type IEND struct {
}
IEND The IEND chunk must appear LAST. It marks the end of the PNG datastream. The chunk's data field is empty.
type IHDR ¶
type IHDR struct {
Width uint32
Height uint32
BitDepth uint8
ColorType uint8
CompressionMethod uint8
FilterMethod uint8
InterlaceMethod uint8
}
IHDR The IHDR chunk must appear FIRST. It contains:
Width: 4 bytes Height: 4 bytes Bit depth: 1 byte Color type: 1 byte Compression method: 1 byte Filter method: 1 byte Interlace method: 1 byte
Width and height give the image dimensions in pixels. They are 4-byte integers. Zero is an invalid value. The maximum for each is (2^31)-1 in order to accommodate languages that have difficulty with unsigned 4-byte values. Bit depth is a single-byte integer giving the number of bits per sample or per palette index (not per pixel). Valid values are 1, 2, 4, 8, and 16, although not all values are allowed for all color types.
Color type is a single-byte integer that describes the interpretation of the image data. Color type codes represent sums of the following values: 1 (palette used), 2 (color used), and 4 (alpha channel used). Valid values are 0, 2, 3, 4, and 6.
Bit depth restrictions for each color type are imposed to simplify implementations and to prohibit combinations that do not compress well. Decoders must support all legal combinations of bit depth and color type. The allowed combinations are:
Color Allowed Interpretation
Type Bit Depths
0 1,2,4,8,16 Each pixel is a grayscale sample.
2 8,16 Each pixel is an R,G,B triple.
3 1,2,4,8 Each pixel is a palette index;
a PLTE chunk must appear.
4 8,16 Each pixel is a grayscale sample,
followed by an alpha sample.
6 8,16 Each pixel is an R,G,B triple,
followed by an alpha sample.
The sample depth is the same as the bit depth except in the case of color type 3, in which the sample depth is always 8 bits. Compression method is a single-byte integer that indicates the method used to compress the image data. At present, only compression method 0 (deflate/inflate compression with a 32K sliding window) is defined. All standard PNG images must be compressed with this scheme. The compression method field is provided for possible future expansion or proprietary variants. Decoders must check this byte and report an error if it holds an unrecognized code. See Deflate/Inflate Compression for details.
Filter method is a single-byte integer that indicates the preprocessing method applied to the image data before compression. At present, only filter method 0 (adaptive filtering with five basic filter types) is defined. As with the compression method field, decoders must check this byte and report an error if it holds an unrecognized code. See Filter Algorithms for details.
Interlace method is a single-byte integer that indicates the transmission order of the image data. Two values are currently defined: 0 (no interlace) or 1 (Adam7 interlace). See Interlaced data order for details.
type ITXT ¶ added in v1.1.0
type ITXT struct {
Keyword string
CompressionFlag uint8
CompressionMethod uint8
LanguageTag string
TranslatedKeyword string
Text string
// Data keeps the raw chunk payload.
Data []byte
}
ITXT
The iTXt chunk contains textual data just like tEXt and zTXt, but the text is UTF-8 encoded and both the translated keyword and the text itself can be compressed. XMP metadata in png files is stored as an iTXt chunk with the keyword "XML:com.adobe.xmp". The chunk layout is:
Keyword: 1-79 bytes (character string) Null separator: 1 byte Compression flag: 1 byte (0: uncompressed, 1: compressed) Compression method: 1 byte (0: zlib) Null separator: 1 byte Language tag (LCID): n bytes of ASCII, implicit "x-default" if empty Null separator: 1 byte Translated keyword: n bytes of UTF-8 Null separator: 1 byte Text: n bytes of UTF-8 (optionally zlib compressed)
type PHYS ¶
PHYS The pHYs chunk specifies the intended pixel size or aspect ratio for display of the image. It contains:
Pixels per unit, X axis: 4 bytes (unsigned integer) Pixels per unit, Y axis: 4 bytes (unsigned integer) Unit specifier: 1 byte
The following values are legal for the unit specifier:
0: unit is unknown 1: unit is the meter
When the unit specifier is 0, the pHYs chunk defines pixel aspect ratio only; the actual size of the pixels remains unspecified. Conversion note: one inch is equal to exactly 0.0254 meters.
If this ancillary chunk is not present, pixels are assumed to be square, and the physical size of each pixel is unknown.
If present, this chunk must precede the first IDAT chunk.
See Recommendations for Decoders: Pixel dimensions.
type PLTE ¶
type PLTE struct {
Colors []*PLTEColor
}
PLTE
The PLTE chunk contains from 1 to 256 palette entries, each a three-byte series of the form: Red: 1 byte (0 = black, 255 = red) Green: 1 byte (0 = black, 255 = green) Blue: 1 byte (0 = black, 255 = blue)
The number of entries is determined from the chunk length. A chunk length not divisible by 3 is an error. This chunk must appear for color type 3, and can appear for color types 2 and 6; it must not appear for color types 0 and 4. If this chunk does appear, it must precede the first IDAT chunk. There must not be more than one PLTE chunk.
For color type 3 (indexed color), the PLTE chunk is required. The first entry in PLTE is referenced by pixel value 0, the second by pixel value 1, etc. The number of palette entries must not exceed the range that can be represented in the image bit depth (for example, 2^4 = 16 for a bit depth of 4). It is permissible to have fewer entries than the bit depth would allow. In that case, any out-of-range pixel value found in the image data is an error.
For color types 2 and 6 (truecolor and truecolor with alpha), the PLTE chunk is optional. If present, it provides a suggested set of from 1 to 256 colors to which the truecolor image can be quantized if the viewer cannot display truecolor directly. If PLTE is not present, such a viewer will need to select colors on its own, but it is often preferable for this to be done once by the encoder. (See Recommendations for Encoders: Suggested palettes.)
Note that the palette uses 8 bits (1 byte) per sample regardless of the image bit depth specification. In particular, the palette is 8 bits deep even when it is a suggested quantization of a 16-bit truecolor image.
There is no requirement that the palette entries all be used by the image, nor that they all be different.
type Png ¶
type Png struct {
Width, Height int
Channel int
sync.RWMutex
sync.Once
IHDR *IHDR
IDATs []*IDAT
PLTE *PLTE
BKGD *BKGD
CHRM *CHRM
GAMA *GAMA
HIST *HIST
PHYS *PHYS
SBIT *SBIT
TEXTs []*TEXT
TRNS *TRNS
TIME *TIME
ZTXTs []*ZTXT
ITXTs []*ITXT
ICCP *ICCP
SRGB *SRGB
EXIF *EXIF
IEND *IEND
OtherChunk map[ChunkName][]ChunkParse
// contains filtered or unexported fields
}
func ParsePng ¶
ParsePng parses a png stream: it reads the signature and all chunks, decodes the base chunks (IHDR, IDAT, PLTE and the metadata chunks) and keeps every not-consumed chunk in raw form (see RawChunks). CRC-32 verification of each chunk is optional and off by default, pass verifyCRC=true to reject streams with a mismatching chunk CRC.
func (*Png) AddRawChunk ¶ added in v1.1.0
AddRawChunk inserts a new raw chunk into the stream before the first IDAT chunk (ancillary chunks must precede the first IDAT; if the file has no IDAT it goes right before IEND). You cannot add the single-occurrence IHDR, IDAT or IEND chunks with it. The CRC is computed over the given data and the chunk appears as a raw chunk (see RawChunks) and in WriteTo output. Use it e.g. with NewITXTChunk to embed XMP metadata into an untouched file. It is safe to call concurrently with the other editing methods and the readers of the same instance.
func (*Png) DeleteRawChunk ¶ added in v1.1.0
DeleteRawChunk removes every remaining chunk of the given type from the stream and returns how many chunks were removed. A WriteTo afterwards writes the stream without those chunks. It is safe to call concurrently with the other editing methods and the readers of the same instance.
func (*Png) GetOtherChunkByName ¶
func (p *Png) GetOtherChunkByName(name ChunkName) ([]ChunkParse, error)
func (*Png) IDATsToColor ¶ added in v1.1.0
IDATsToColor decodes the image: it concatenates and decompresses all IDAT chunks, reverses the scanline filtering and converts the pixels to a standard library image.Image (Grayscale/Gray16, RGBA/RGBA64, NRGBA/NRGBA64 or Paletted depending on the color type and bit depth).
tRNS simple transparency is applied to grayscale, truecolor and palette images. Adam7 interlaced images are supported.
The pixel decode runs under the internal read lock: it is safe to decode concurrently with other readers of the same instance, while editing methods block until the decode has finished.
func (*Png) MarshalBytes ¶ added in v1.1.0
MarshalBytes returns the png stream of the current state as a byte slice, see WriteTo for the details.
func (*Png) ParseChunk ¶
func (p *Png) ParseChunk(c ChunkParse, notSave ...bool) error
ParseChunk parses the first chunk whose type code matches c.ChunkName(). After a successful parse the chunk is consumed and removed from the raw chunk list. Unless notSave is true, the parser instance is recorded in OtherChunk and can be retrieved later with GetOtherChunkByName. If no matching chunk exists, chunkNotFoundErr is returned and nothing is modified.
The whole operation runs under the internal write lock, so concurrent ParseChunk / AddRawChunk / DeleteRawChunk / WriteTo calls on the same instance are serialized. The Parse callback of the given chunk must not call back into the same Png instance (a RWMutex is not reentrant).
func (*Png) RawChunkByName ¶ added in v1.1.0
RawChunkByName returns the raw data of the first still-present chunk of the given type, for use cases like reading XMP (iTXt, parsed natively) or EXIF (eXIf) metadata that has no dedicated struct yet.
func (*Png) RawChunks ¶ added in v1.1.0
RawChunks returns all chunks that are still left after base parsing, in the order they appear in the file. Use this for chunk types the library does not decode natively yet, like eXIf, sRGB or iCCP.
func (*Png) ReplaceImage ¶ added in v1.1.0
ReplaceImage re-encodes the pixels of img and swaps them into an already parsed png, keeping every other chunk (metadata like tEXt, iTXt/XMP, tIME, raw chunks...) and its position in the stream untouched. The new image must match the color type and bit depth of the file (any size is allowed): the IHDR and the reported image dimensions are updated. Use it to replace the pixels of an existing file without losing its metadata. The whole operation runs under the internal write lock, so it is safe to call concurrently with the other editing methods and the readers of the same instance.
func (*Png) WriteTo ¶ added in v1.1.0
WriteTo writes the png stream of the current state, implementing io.WriterTo (so it works with io.Copy). Chunks that were consumed while parsing are re-serialized from their parsed structs, so any modifications made to the structs (or chunks added/deleted through AddRawChunk / DeleteRawChunk) are reflected, while the chunks that were left raw are copied verbatim. Parsing and writing back a file without touching anything reproduces it byte for byte. The CRC of every written chunk is recomputed.
Note: the compressed text chunks (zTXt and iTXt with the compression flag set) are preserved byte for byte unless their Text field was modified, in which case they are re-compressed with the default zlib level.
Reading is guarded by the internal read lock: it is safe to write back while other goroutines read metadata through RawChunks / GetOtherChunkByName, while concurrent writes on the same instance are serialized with the editing methods.
type RawChunk ¶ added in v1.1.0
type RawChunk struct {
// Name is the 4 byte chunk type code, e.g. "sRGB" or "eXIf".
Name ChunkName
// Data is the raw chunk data (without the length, type and crc fields).
Data []byte
// CRC is the CRC stored in the file (verified during reading only when
// verifyCRC was passed to ParsePng).
CRC uint32
}
RawChunk is a chunk that was left in the file and is not decoded natively yet, exposed in its raw form. It can also be parsed with a custom chunk type through ParseChunk.
type SBIT ¶
type SBIT struct {
OrgData [4]byte
}
SBIT
To simplify decoders, PNG specifies that only certain sample depths can be used, and further specifies that sample values should be scaled to the full range of possible values at the sample depth. However, the sBIT chunk is provided in order to store the original number of significant bits. This allows decoders to recover the original data losslessly even if the data had a sample depth not directly supported by PNG. We recommend that an encoder emit an sBIT chunk if it has converted the data from a lower sample depth. For color type 0 (grayscale), the sBIT chunk contains a single byte, indicating the number of bits that were significant in the source data.
For color type 2 (truecolor), the sBIT chunk contains three bytes, indicating the number of bits that were significant in the source data for the red, green, and blue channels, respectively.
For color type 3 (indexed color), the sBIT chunk contains three bytes, indicating the number of bits that were significant in the source data for the red, green, and blue components of the palette entries, respectively.
For color type 4 (grayscale with alpha channel), the sBIT chunk contains two bytes, indicating the number of bits that were significant in the source grayscale data and the source alpha data, respectively.
For color type 6 (truecolor with alpha channel), the sBIT chunk contains four bytes, indicating the number of bits that were significant in the source data for the red, green, blue and alpha channels, respectively.
Each depth specified in sBIT must be greater than zero and less than or equal to the sample depth (which is 8 for indexed-color images, and the bit depth given in IHDR for other color types).
A decoder need not pay attention to sBIT: the stored image is a valid PNG file of the sample depth indicated by IHDR. However, if the decoder wishes to recover the original data at its original precision, this can be done by right-shifting the stored samples (the stored palette entries, for an indexed-color image). The encoder must scale the data in such a way that the high-order bits match the original data.
If the sBIT chunk appears, it must precede the first IDAT chunk, and it must also precede the PLTE chunk if present.
See Recommendations for Encoders: Sample depth scaling and Recommendations for Decoders: Sample depth rescaling.
type SRGB ¶ added in v1.1.0
type SRGB struct {
RenderingIntent uint8
}
SRGB The sRGB chunk conveys the legacy sRGB gamma, chromaticity, luminance, and color data. It contains:
Rendering intent: 1 byte
Legal rendering intents are:
0: perceptual 1: relative colorimetric 2: saturation 3: absolute colorimetric
A PNG datastream shall contain no more than one sRGB chunk. A decoder encountering both iCCP and sRGB chunks is free to pick one. This library keeps both present in width and leaves the decision to the caller.
If present, this chunk must precede the first IDAT chunk.
type TEXT ¶
TEXT
Textual information that the encoder wishes to record with the image can be stored in tEXt chunks. Each tEXt chunk contains a keyword and a text string, in the format:
Keyword: 1-79 bytes (character string) Null separator: 1 byte Text: n bytes (character string)
The keyword and text string are separated by a zero byte (null character). Neither the keyword nor the text string can contain a null character. Note that the text string is not null-terminated (the length of the chunk is sufficient information to locate the ending). The keyword must be at least one character and less than 80 characters long. The text string can be of any length from zero bytes up to the maximum permissible chunk size less the length of the keyword and separator.
type TIME ¶
TIME
The tIME chunk gives the time of the last image modification (not the time of initial image creation). It contains:
Year: 2 bytes (complete; for example, 1995, not 95)
Month: 1 byte (1-12)
Day: 1 byte (1-31)
Hour: 1 byte (0-23)
Minute: 1 byte (0-59)
Second: 1 byte (0-60) (yes, 60, for leap seconds; not 61,
a common error)
Universal Time (UTC, also called GMT) should be specified rather than local time. The tIME chunk is intended for use as an automatically-applied time stamp that is updated whenever the image data is changed. It is recommended that tIME not be changed by PNG editors that do not change the image data. See also the Creation Time tEXt keyword, which can be used for a user-supplied time.
type TRNS ¶
type TRNS struct {
// For color type 3 (indexed color): alpha values for the first len(PaletteAlphas) palette entries.
PaletteAlphas []uint8
// For color types 0 and 4 (grayscale): the gray level to be treated as transparent.
Gray uint16
// For color type 2 (truecolor): the rgb color to be treated as transparent.
Red uint16
Green uint16
Blue uint16
// Data keeps the raw chunk payload, see TRNS.Data usage in IDATsToColor.
Data []byte
}
TRNS The tRNS chunk specifies that the image uses simple transparency: either alpha values associated with palette entries (for indexed-color images) or a single transparent color (for grayscale and truecolor images). Although simple transparency is not as elegant as the full alpha channel, it requires less storage space and is sufficient for many common cases. For color type 3 (indexed color), the tRNS chunk contains a series of one-byte alpha values, corresponding to entries in the PLTE chunk:
Alpha for palette index 0: 1 byte Alpha for palette index 1: 1 byte ... etc ...
Each entry indicates that pixels of the corresponding palette index must be treated as having the specified alpha value. Alpha values have the same interpretation as in an 8-bit full alpha channel: 0 is fully transparent, 255 is fully opaque, regardless of image bit depth. The tRNS chunk must not contain more alpha values than there are palette entries, but tRNS can contain fewer values than there are palette entries. In this case, the alpha value for all remaining palette entries is assumed to be 255. In the common case in which only palette index 0 need be made transparent, only a one-byte tRNS chunk is needed. For color type 0 (grayscale), the tRNS chunk contains a single gray level value, stored in the format:
Gray: 2 bytes, range 0 .. (2^bitdepth)-1
(For consistency, 2 bytes are used regardless of the image bit depth.) Pixels of the specified gray level are to be treated as transparent (equivalent to alpha value 0); all other pixels are to be treated as fully opaque (alpha value (2^bitdepth)-1). For color type 2 (truecolor), the tRNS chunk contains a single RGB color value, stored in the format:
Red: 2 bytes, range 0 .. (2^bitdepth)-1 Green: 2 bytes, range 0 .. (2^bitdepth)-1 Blue: 2 bytes, range 0 .. (2^bitdepth)-1
(For consistency, 2 bytes per sample are used regardless of the image bit depth.) Pixels of the specified color value are to be treated as transparent (equivalent to alpha value 0); all other pixels are to be treated as fully opaque (alpha value (2^bitdepth)-1). tRNS is prohibited for color types 4 and 6, since a full alpha channel is already present in those cases.
Note: when dealing with 16-bit grayscale or truecolor data, it is important to compare both bytes of the sample values to determine whether a pixel is transparent. Although decoders may drop the low-order byte of the samples for display, this must not occur until after the data has been tested for transparency. For example, if the grayscale level 0x0001 is specified to be transparent, it would be incorrect to compare only the high-order byte and decide that 0x0002 is also transparent.
When present, the tRNS chunk must precede the first IDAT chunk, and must follow the PLTE chunk, if any.
func (*TRNS) Parse ¶
Parse fills the fields of TRNS based on the length of the chunk data: two bytes are a gray level and six bytes are an rgb color, any other length is a list of palette alpha values. Note that a tRNS chunk for a palette image with exactly two (or six) entries is indistinguishable from a gray level (or rgb color) without knowing the color type from IHDR; IDATsToColor re-interprets TRNS.Data with the actual color type when decoding.
type ZTXT ¶
ZTXT The zTXt chunk contains textual data, just as tEXt does; however, zTXt takes advantage of compression. zTXt and tEXt chunks are semantically equivalent, but zTXt is recommended for storing large blocks of text. A zTXt chunk contains:
Keyword: 1-79 bytes (character string) Null separator: 1 byte Compression method: 1 byte Compressed text: n bytes
The keyword and null separator are exactly the same as in the tEXt chunk. Note that the keyword is not compressed. The compression method byte identifies the compression method used in this zTXt chunk. The only value presently defined for it is 0 (deflate/inflate compression). The compression method byte is followed by a compressed datastream that makes up the remainder of the chunk. For compression method 0, this datastream adheres to the zlib datastream format (see Deflate/Inflate Compression). Decompression of this datastream yields Latin-1 text that is identical to the text that would be stored in an equivalent tEXt chunk. Any number of zTXt and tEXt chunks can appear in the same file. See the preceding definition of the tEXt chunk for the predefined keywords and the recommended format of the text.
See Recommendations for Encoders: Text chunk processing, and Recommendations for Decoders: Text chunk processing.