pngn

package module
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 16 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

pngn

Status Go Reference

PNG and APNG image decoder and encoder in pure Go, a drop-in replacement for image/png.

SIMD support for amd64 (SSE4.1, AVX2), arm64 (NEON) and riscv64 (RVV, with GORISCV64=rva23u64). Build with -tags noasm for pure Go everywhere.

github.com/gen2brain/pngn/flate is the DEFLATE and zlib codec underneath, exported for whole buffers in memory.

Differences from image/png

  • Animation, DecodeAll and EncodeAll
  • EXIF, and the orientation applied on request
  • Text, ICC profiles, color space, HDR and every other ancillary chunk, read and written
  • Chunks it does not interpret survive a decode and re-encode
  • A truncated file gives back the rows it carried instead of an error
  • A wrong CRC is decodable on request
  • Adam7 interlacing on encode, and a selectable row filter

License

MIT, in LICENSE.

Documentation

Overview

Package pngn decodes and encodes PNG images.

img, err := pngn.Decode(r)

Decode returns *image.Gray, *image.Gray16, *image.NRGBA, *image.NRGBA64, *image.Paletted, *image.RGBA or *image.RGBA64, the same type image/png returns for the same input. The package registers itself with image.RegisterFormat.

Every color type and bit depth the specification defines is read, with or without Adam7 interlacing, and tRNS is applied. A malformed file gives ErrInvalid and a well formed one this package cannot decode gives ErrUnsupported.

img, err := pngn.Decode(r, &pngn.Options{PixelLimit: 1 << 24})

DecodeConfig reports the dimensions and color model as the header stores them.

Encoding

err := pngn.Encode(w, img)

Encode chooses the color type and bit depth from the image, the same way image/png does, so a decode and a re-encode keeps a file's shape. EncodeOptions selects the compression level, the row filter, and Adam7 interlacing, which image/png cannot write.

err := pngn.Encode(w, img, &pngn.EncodeOptions{
	CompressionLevel: pngn.BestCompression,
	Interlace:        true,
})

Metadata

Metadata holds every ancillary chunk: text, EXIF, an ICC profile, the color space and HDR chunks, physical size, time, and the chunks this package does not interpret. DecodeMetadata reads them without decoding pixels, and EncodeOptions.Metadata writes them, so a decode and re-encode keeps what image/png throws away.

meta, err := pngn.DecodeMetadata(r)

err := pngn.Encode(w, img, &pngn.EncodeOptions{
	Metadata: &pngn.Metadata{
		Text: []pngn.Text{{Keyword: "Software", Value: "pngn"}},
	},
})

DecodeExif parses the eXIf chunk and Options.AutoRotate applies the orientation it carries.

Damaged files

Options.Partial returns the rows a truncated file did carry rather than an error, which is what a viewer wants from a download that stopped. Options.IgnoreCRC decodes a chunk whose checksum is wrong. Neither is on by default, and nothing this package decodes panics on any input.

Animation

anim, err := pngn.DecodeAll(r)

DecodeAll returns every frame of an APNG, composited onto the canvas and the size of it, with the delay of each in seconds and the loop count. A file with no acTL chunk comes back as one frame. EncodeAll writes one, using the first frame as the default image so that a decoder which does not know APNG still sees something, and writing each later frame as only the rectangle it changes.

Index

Constants

View Source
const DefaultPixelLimit = min(1<<28, math.MaxInt>>6)

DefaultPixelLimit is the image area, in pixels, accepted when Options.PixelLimit is zero. It is smaller on a 32 bit platform.

Variables

View Source
var (
	ErrInvalid     = errors.New("invalid PNG")
	ErrUnsupported = errors.New("unsupported PNG feature")
)

Errors returned by this package.

Functions

func Animated added in v0.1.3

func Animated(r io.Reader) (bool, error)

Animated reports whether r holds an APNG, reading no further than the acTL chunk an animation declares before its first frame.

func Decode

func Decode(r io.Reader, opts ...*Options) (image.Image, error)

Decode reads a PNG image from r and returns it as an image.Image.

func DecodeConfig

func DecodeConfig(r io.Reader) (image.Config, error)

DecodeConfig returns the color model and dimensions of a PNG image without decoding the pixels. Both are as the header stores them.

func Encode

func Encode(w io.Writer, m image.Image, opts ...*EncodeOptions) error

Encode writes m to w in PNG format.

func EncodeAll

func EncodeAll(w io.Writer, a *PNG, opts ...*EncodeOptions) error

EncodeAll writes an animated PNG, with the first frame as the default image.

func RawExif

func RawExif(r io.Reader) ([]byte, error)

RawExif returns the eXIf payload verbatim, for EncodeOptions.

Types

type Background

type Background struct {
	Index   uint8
	Gray    uint16
	R, G, B uint16
}

Background is the bKGD chunk; the color type selects the field used.

type CICP

type CICP struct {
	ColorPrimaries          uint8
	TransferCharacteristics uint8
	MatrixCoefficients      uint8
	FullRange               bool
}

CICP is the cICP chunk.

type Chroma

type Chroma struct {
	WhiteX, WhiteY uint32
	RedX, RedY     uint32
	GreenX, GreenY uint32
	BlueX, BlueY   uint32
}

Chroma is the cHRM chunk, CIE 1931 chromaticities times 100000.

type Chunk

type Chunk struct {
	// Type is the four character chunk type code.
	Type string

	// Data is the payload, without the length, type or CRC.
	Data []byte

	// After reports that the chunk followed IDAT.
	After bool
}

Chunk is an ancillary chunk carried through unchanged.

type CompressionLevel

type CompressionLevel int

CompressionLevel is the DEFLATE level an image is written at.

const (
	DefaultCompression CompressionLevel = 0
	NoCompression      CompressionLevel = -1
	BestSpeed          CompressionLevel = 1
	BestCompression    CompressionLevel = 9
)

type ContentLight

type ContentLight struct {
	MaxCLL  uint32
	MaxFALL uint32
}

ContentLight is the cLLI chunk, in units of 0.0001 cd/m2.

type EncodeOptions

type EncodeOptions struct {
	// CompressionLevel is 1 to 9, [NoCompression], or zero for
	// [DefaultCompression].
	CompressionLevel CompressionLevel

	// Filter selects the row filter. The zero value is [FilterAdaptive].
	Filter FilterMethod

	// Interlace writes the image in seven Adam7 passes.
	Interlace bool

	// Metadata is the ancillary chunks to write.
	Metadata *Metadata
}

EncodeOptions specifies encoding parameters.

type Exif

type Exif struct {
	// Orientation is 1 to 8; 1 is upright.
	Orientation int

	// Width and Height are what the EXIF tags claim, not the IHDR.
	Width, Height int

	Make     string
	Model    string
	Software string

	// DateTime and DateTimeOriginal are "YYYY:MM:DD HH:MM:SS".
	DateTime         string
	DateTimeOriginal string

	// ExposureTime is in seconds and FocalLength in millimetres.
	ExposureTime float64
	FNumber      float64
	ISOSpeed     int
	FocalLength  float64
	Flash        int

	// GPSLatitude and GPSLongitude are decimal degrees, GPSAltitude metres.
	GPSLatitude  float64
	GPSLongitude float64
	GPSAltitude  float64

	Copyright string
	Artist    string
}

Exif is the metadata an eXIf chunk carries. An absent tag stays zero.

func DecodeExif

func DecodeExif(r io.Reader) (*Exif, error)

DecodeExif reads the eXIf chunk of a PNG and parses it.

type FilterMethod

type FilterMethod int

FilterMethod selects how each row is filtered before compression.

const (
	// FilterAdaptive picks the filter with the smallest sum of absolute
	// deviations, per row. It is what libpng and image/png do.
	FilterAdaptive FilterMethod = iota
	FilterNone
	FilterSub
	FilterUp
	FilterAverage
	FilterPaeth
)

type ICCProfile

type ICCProfile struct {
	// Name is 1 to 79 Latin-1 characters.
	Name string

	// Profile is the ICC profile itself, uncompressed.
	Profile []byte
}

ICCProfile is the iCCP chunk.

type MasteringDisplay

type MasteringDisplay struct {
	RedX, RedY     uint16
	GreenX, GreenY uint16
	BlueX, BlueY   uint16
	WhiteX, WhiteY uint16

	MaxLuminance uint32
	MinLuminance uint32
}

MasteringDisplay is the mDCV chunk, chromaticities in units of 0.00002 and luminances in units of 0.0001 cd/m2.

type Metadata

type Metadata struct {
	// Text is every tEXt, zTXt and iTXt chunk, in file order.
	Text []Text

	// Exif is the eXIf payload, a TIFF header and the IFDs after it.
	Exif []byte

	// ICCProfile is the iCCP chunk, decompressed.
	ICCProfile *ICCProfile

	// Gamma is the gAMA chunk, the image gamma times 100000.
	Gamma uint32

	// Chroma is the cHRM chunk.
	Chroma *Chroma

	// RenderingIntent is the sRGB chunk.
	RenderingIntent *RenderingIntent

	// CICP is the cICP chunk.
	CICP *CICP

	// MasteringDisplay is the mDCV chunk.
	MasteringDisplay *MasteringDisplay

	// ContentLight is the cLLI chunk.
	ContentLight *ContentLight

	// Physical is the pHYs chunk.
	Physical *Physical

	// Time is the tIME chunk, in UTC.
	Time *time.Time

	// SignificantBits is the sBIT chunk.
	SignificantBits *SignificantBits

	// Background is the bKGD chunk.
	Background *Background

	// Histogram is the hIST chunk, one frequency per palette entry.
	Histogram []uint16

	// SuggestedPalettes is every sPLT chunk.
	SuggestedPalettes []SuggestedPalette

	// Unknown is every ancillary chunk not interpreted here, in file order.
	Unknown []Chunk
}

Metadata holds the ancillary chunks of a PNG. A zero field is an absent chunk.

func DecodeMetadata

func DecodeMetadata(r io.Reader, opts ...*Options) (*Metadata, error)

DecodeMetadata reads every ancillary chunk of a PNG without decoding pixels.

type Options

type Options struct {
	// PixelLimit bounds an image's area in pixels. Zero means
	// [DefaultPixelLimit]; a negative value removes the limit.
	PixelLimit int

	// Metadata, when not nil, is filled with the file's ancillary chunks.
	Metadata *Metadata

	// AutoRotate applies the orientation the eXIf chunk carries.
	AutoRotate bool

	// IgnoreCRC decodes a chunk whose checksum is wrong.
	IgnoreCRC bool

	// Partial returns the rows a truncated file did carry, with no error.
	Partial bool
}

Options specifies decoding parameters.

type PNG

type PNG struct {
	// Image is every frame, composited and the size of the canvas.
	Image []image.Image

	// Delay is one duration per frame, in seconds.
	Delay []float64

	// LoopCount is the repeat count; zero repeats forever.
	LoopCount int
}

PNG is a decoded animation.

func DecodeAll

func DecodeAll(r io.Reader, opts ...*Options) (*PNG, error)

DecodeAll reads every frame of an animated PNG. A file with no acTL chunk comes back as a single frame.

type Physical

type Physical struct {
	X, Y uint32
	Unit PhysicalUnit
}

Physical is the pHYs chunk.

type PhysicalUnit

type PhysicalUnit uint8

PhysicalUnit is the unit a pHYs chunk counts in.

const (
	UnitUnknown PhysicalUnit = iota
	UnitMetre
)

The units the specification defines.

type RenderingIntent

type RenderingIntent uint8

RenderingIntent is the sRGB chunk.

const (
	Perceptual RenderingIntent = iota
	RelativeColorimetric
	Saturation
	AbsoluteColorimetric
)

The rendering intents the specification defines.

type SignificantBits

type SignificantBits struct {
	Gray             uint8
	Red, Green, Blue uint8
	Alpha            uint8
}

SignificantBits is the sBIT chunk; the color type selects the fields used.

type SuggestedPalette

type SuggestedPalette struct {
	// Name is 1 to 79 Latin-1 characters.
	Name string

	// Depth is 8 or 16; Entries hold 16 bit values either way.
	Depth uint8

	Entries []SuggestedPaletteEntry
}

SuggestedPalette is an sPLT chunk.

type SuggestedPaletteEntry

type SuggestedPaletteEntry struct {
	R, G, B, A uint16
	Frequency  uint16
}

SuggestedPaletteEntry is one entry of an sPLT chunk.

type Text

type Text struct {
	// Keyword is 1 to 79 Latin-1 characters.
	Keyword string

	// Value is the text.
	Value string

	// Language is an iTXt language tag and Translated the keyword in it.
	Language   string
	Translated string

	// Compressed selects zTXt, or iTXt with its compression flag set.
	Compressed bool

	// International selects iTXt, as does a value Latin-1 cannot hold.
	International bool
}

Text is a tEXt, zTXt or iTXt chunk.

Directories

Path Synopsis
Package flate compresses and decompresses DEFLATE and zlib streams.
Package flate compresses and decompresses DEFLATE and zlib streams.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址