png

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2024 License: BSD-3-Clause Imports: 18 Imported by: 0

Documentation

Overview

Package png implements a PNG image decoder and encoder.

The PNG specification is at https://www.w3.org/TR/PNG/.

Index

Examples

Constants

View Source
const (
	SpacePerceptual           = 0
	SpaceRelativeColorimetric = 1
	SpaceSaturation           = 2
	SpaceAbsoluteColorimetric = 3
)
View Source
const (
	UnitUnknown = 0
	UnitMeter   = 1
)

Variables

This section is empty.

Functions

func Decode

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

Decode reads a PNG image from r and returns it as an image.Image. The type of Image returned depends on the PNG contents.

Note this function is deprecated. Use DecodeExtended instead.

Example
package main

import (
	"context"
	"encoding/base64"
	"fmt"
	"io"
	"log"
	"strings"

	"github.com/Coder-na-r1/image"
	"github.com/Coder-na-r1/image/color"
	"github.com/Coder-na-r1/image/png"
)

const gopher = `iVBORw0KGgoAAAANSUhEUgAAAEsAAAA8CAAAAAALAhhPAAAFfUlEQVRYw62XeWwUVRzHf2+OPbo9d7tsWyiyaZti6eWGAhISoIGKECEKCAiJJkYTiUgTMYSIosYYBBIUIxoSPIINEBDi2VhwkQrVsj1ESgu9doHWdrul7ba73WNm3vOPtsseM9MdwvvrzTs+8/t95ze/33sI5BqiabU6m9En8oNjduLnAEDLUsQXFF8tQ5oxK3vmnNmDSMtrncks9Hhtt/qeWZapHb1ha3UqYSWVl2ZmpWgaXMXGohQAvmeop3bjTRtv6SgaK/Pb9/bFzUrYslbFAmHPp+3WhAYdr+7GN/YnpN46Opv55VDsJkoEpMrY/vO2BIYQ6LLvm0ThY3MzDzzeSJeeWNyTkgnIE5ePKsvKlcg/0T9QMzXalwXMlj54z4c0rh/mzEfr+FgWEz2w6uk8dkzFAgcARAgNp1ZYef8bH2AgvuStbc2/i6CiWGj98y2tw2l4FAXKkQBIf+exyRnteY83LfEwDQAYCoK+P6bxkZm/0966LxcAAILHB56kgD95PPxltuYcMtFTWw/FKkY/6Op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h9R4Nye3nRDk199V+aetmvVtDRE8/+cbgAAgMIWGb3UA0MGLE9SCbWX670TDy1y98c3D27eppUjsZ6fql3jcd5rUe7+ZIlLNQny3Rd+E5Tct3WVhTM5RBCEdiEK0b6B+/ca2gYU393nFj/n1AygRQxPIUA043M42u85+z2SnssKrPl8Mx76NL3E6eXc3be7OD+H4WHbJkKI8AU8irbITQjZ+0hQcPEgId/Fn/pl9crKH02+5o2b9T/eMx7pKoskYgAAAABJRU5ErkJggg==`

// gopherPNG creates an io.Reader by decoding the base64 encoded image data string in the gopher constant.
func gopherPNG() io.Reader { return base64.NewDecoder(base64.StdEncoding, strings.NewReader(gopher)) }

func main() {
	// This example uses png.DecodeExtended which can only decode PNG
	// images.  Consider using the general image.DecodeImage as it can
	// sniff and decode any registered image format.
	ctx := context.TODO()
	img, _, err := png.DecodeExtended(ctx, gopherPNG(), image.OptionDecodeImage)
	if err != nil {
		log.Fatal(err)
	}

	levels := []string{" ", "░", "▒", "▓", "█"}

	for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ {
		for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ {
			c := color.GrayModel.Convert(img.At(x, y)).(color.Gray)
			level := c.Y / 51 // 51 * 5 = 255
			if level == 5 {
				level--
			}
			fmt.Print(levels[level])
		}
		fmt.Print("\n")
	}
}
Output:

func DecodeConfig

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

DecodeConfig returns the color model and dimensions of a PNG image without decoding the entire image. Note this function is deprecated. Use DecodeExtended and fetch the config from the metadata object instead.

func DecodeExtended

func DecodeExtended(ctx context.Context, r io.Reader, opts ...image.ReadOption) (image.Image, image.Metadata, error)

func Encode

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

Encode writes the Image m to w in PNG format. Any Image may be encoded, but images that are not image.NRGBA might be encoded lossily.

Example
package main

import (
	"log"
	"os"

	"github.com/Coder-na-r1/image"
	"github.com/Coder-na-r1/image/color"
	"github.com/Coder-na-r1/image/png"
)

func main() {
	const width, height = 256, 256

	// Create a colored image of the given width and height.
	img := image.NewNRGBA(image.Rect(0, 0, width, height))

	for y := 0; y < height; y++ {
		for x := 0; x < width; x++ {
			img.Set(x, y, color.NRGBA{
				R: uint8((x + y) & 255),
				G: uint8((x + y) << 1 & 255),
				B: uint8((x + y) << 2 & 255),
				A: 255,
			})
		}
	}

	f, err := os.Create("image.png")
	if err != nil {
		log.Fatal(err)
	}

	if err := png.Encode(f, img); err != nil {
		f.Close()
		log.Fatal(err)
	}

	if err := f.Close(); err != nil {
		log.Fatal(err)
	}
}
Output:

func EncodeExtended

func EncodeExtended(ctx context.Context, w io.Writer, m image.Image, opts ...image.WriteOption) error

Types

type Background

type Background struct {
	Grey         int
	Red          int
	Green        int
	Blue         int
	PaletteIndex int
}

Background holds the background color for an image. Not all fields are relevant for an image.

func (Background) String

func (b Background) String() string

String generates a human readable version of the background color specifier.

type Chroma

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

type CompressionLevel

type CompressionLevel int
const (
	DefaultCompression CompressionLevel = 0
	NoCompression      CompressionLevel = -1
	BestSpeed          CompressionLevel = -2
	BestCompression    CompressionLevel = -3
)

type Deferred

type Deferred struct {
	// contains filtered or unexported fields
}

Deferred holds a PNG image that hasn't yet been parsed. It proxies the standard image functions, and will parse the underlying cached image either when Instantiate is explicitly called or when one of the standard image methods are invoked.

If a deferred image is passed to Encode or EncodeExtended then it will write out the same image contents as were read in.

func (*Deferred) At

func (d *Deferred) At(x, y int) color.Color

func (*Deferred) Bounds

func (d *Deferred) Bounds() image.Rectangle

func (*Deferred) ColorModel

func (d *Deferred) ColorModel() color.Model

func (*Deferred) Instantiate

func (i *Deferred) Instantiate(ctx context.Context, opts ...image.ReadOption) (image.Image, error)

type Dimension

type Dimension struct {
	X    int
	Y    int
	Unit int
}

func (Dimension) String

func (d Dimension) String() string

String generates a human readable version of the Dimension data.

type Encoder

type Encoder struct {
	CompressionLevel CompressionLevel

	// BufferPool optionally specifies a buffer pool to get temporary
	// EncoderBuffers when encoding an image.
	BufferPool EncoderBufferPool
}

Encoder configures encoding PNG images.

func (*Encoder) Encode

func (enc *Encoder) Encode(w io.Writer, m image.Image) error

Encode writes the Image m to w in PNG format.

func (*Encoder) EncodeExtended

func (enc *Encoder) EncodeExtended(ctx context.Context, w io.Writer, m image.Image, opts ...image.WriteOption) error

EncodeExtended writes the Image m to w in PNG format

type EncoderBuffer

type EncoderBuffer encoder

EncoderBuffer holds the buffers used for encoding PNG images.

type EncoderBufferPool

type EncoderBufferPool interface {
	Get() *EncoderBuffer
	Put(*EncoderBuffer)
}

EncoderBufferPool is an interface for getting and returning temporary instances of the EncoderBuffer struct. This can be used to reuse buffers when encoding multiple images.

type FormatError

type FormatError string

A FormatError reports that the input is not a valid PNG.

func (FormatError) Error

func (e FormatError) Error() string

type Metadata

type Metadata struct {

	// Width holds the image width, in pixels
	Width int
	// Height holds the image height, in pixels
	Height int
	// ColorModel holds the color model for this image
	ColorModel color.Model

	Text []*TextEntry

	// LastModified holds the modification timestamp embedded in the PNG
	// image.
	LastModified *time.Time
	// Chroma holds the decoded chroma information for the PNG file
	Chroma *Chroma
	// Gamma holds the decoded gamma data for the PNG file
	Gamma *uint32
	// SRGBIntent holds the SRGB rendering intent for the PNG file
	SRGBIntent *SRGBIntent
	// SignificantBits holds the decoded significant bit data from the
	// sBIT chunk of the PNG file.
	SignificantBits *SignificantBits
	// Background holds the decoded background color from the bKGD chunk
	// of the PNG file.
	Background *Background
	// Dimension holds the pixel size information from the pHYs chunk of
	// the PNG file.
	Dimension *Dimension
	// Histogram holds the histogram data from the hIST chunk of the PNG file.
	Histogram []uint16
	// contains filtered or unexported fields
}

Metadata holds the metadata for a PNG image.

func (*Metadata) EXIF

func (m *Metadata) EXIF(ctx context.Context, opt ...image.ReadOption) (*metadata.EXIF, error)

Exif returns the decoded exif metadata for an image. If there is no exif metadata then it will return nil. The returned exif structure is still associated with its parent metadata object, and changes to it will be persistent.

Note that the exif information may be decoded lazily.

func (*Metadata) GetConfig

func (m *Metadata) GetConfig() image.Config

GetConfig returns the image.Config data extracted from the image's metadata.

func (*Metadata) ICC

func (m *Metadata) ICC(ctx context.Context, opt ...image.ReadOption) (*metadata.ICC, error)

func (*Metadata) ImageMetadataFormat

func (m *Metadata) ImageMetadataFormat() string

ImageMetadataFormat returns the type of image the associated metadata was read from.

func (*Metadata) IsImageWriteOption

func (m *Metadata) IsImageWriteOption()

IsImageWriteOption lets a png metadata struct be passed as a write option to EncodeExtended.

func (*Metadata) SetEXIF

func (m *Metadata) SetEXIF(e *metadata.EXIF)

SetExif replaces the exif information associated with the metdata object.

func (*Metadata) SetIcc

func (m *Metadata) SetIcc(i *metadata.ICC)

func (*Metadata) SetXMP

func (m *Metadata) SetXMP(x *metadata.XMP)

SetXmp replaces the XMP information associated with the metadata object.

func (*Metadata) XMP

func (m *Metadata) XMP(ctx context.Context, opt ...image.ReadOption) (*metadata.XMP, error)

Xmp returns the xmp information associated with the metadata object. If there is no xmp information then it will return nil. The returned xmp structure will still be associated with its parent metadata object, and changes to it will be persistent.

Note that the xmp information may be decoded lazily.

type SRGBIntent

type SRGBIntent uint8

SRGBIntent is the rendering intent as defined by the ICC.

const (
	SIPerceptual SRGBIntent = iota
	SIRelativeColorimetric
	SISaturation
	SIAbsoluteColorimetric
)

func (SRGBIntent) String

func (s SRGBIntent) String() string

String generates a human readable version of the SRGBIntent data.

type SignificantBits

type SignificantBits struct {
	Red   int
	Green int
	Blue  int
	Gray  int
	Alpha int
}

SignificantBits contains the number of significant bits for the red, green, blue, grey, and alpha channels in an image.

type TextEntry

type TextEntry struct {
	// Key is the key for this text entry.
	Key string
	// Value holds the value for this text entry.
	Value string
	// EntryType indicates what kind of entry this is, a regular text
	// entry, compressed text entry, or unicode-encoded text entry.
	EntryType TextType
	// LanguageTag is an RFC-1766 string indicating the language that
	// the translated key and the text is in. This is only valid for
	// unicode text entries.
	LanguageTag string
	// TranslatedKey is the key, translated into the language specified
	// by the language tag. This is only valid for unicode text entries.
	TranslatedKey string
}

TextEntry holds a single entry from a PNG file's key/value data store.

func (*TextEntry) String

func (e *TextEntry) String() string

String generates a human readable version of a text entry.

type TextType

type TextType int
const (
	// EtText indicates an uncompressed 7-bit ascii text entry
	EtText TextType = iota
	// EtZtext indicates a compressed 7-bit ascii text entry
	EtZtext
	// EtItext indicates a compressed unicode text entry
	EtItext
)

func (TextType) String

func (t TextType) String() string

String generates a human readable version of the text entry storage type.

type UnsupportedError

type UnsupportedError string

An UnsupportedError reports that the input uses a valid but unimplemented PNG feature.

func (UnsupportedError) Error

func (e UnsupportedError) Error() string

Jump to

Keyboard shortcuts

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