Spec-Zone.ru › Go

Пакет png

  • import "image/png"
  • Обзор
  • Индекс
  • Примеры

Обзор

Пакет png реализует декодер и кодировщик изображений PNG.

Спецификация PNG находится по адресу https://www.w3.org/TR/PNG/.

Индекс

  • func Decode(r io.Reader) (image.Image, error)
  • func DecodeConfig(r io.Reader) (image.Config, error)
  • func Encode(w io.Writer, m image.Image) error
  • тип CompressionLevel
  • тип Encoder
  • func (enc *Encoder) Encode(w io.Writer, m image.Image) error
  • тип EncoderBuffer
  • тип EncoderBufferPool
  • тип FormatError
  • func (e FormatError) Error() string
  • тип UnsupportedError
  • func (e UnsupportedError) Error() string

Примеры

Декодирование
Кодирование

Файлы пакета

paeth.go reader.go writer.go

func Decode

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

Decode считывает изображение PNG из r и возвращает его как image.Image. Тип возвращаемого Image зависит от содержимого PNG.

Пример

Код:

// This example uses png.Decode which can only decode PNG images.
// Consider using the general image.Decode as it can sniff and decode any registered image format.
img, err := png.Decode(gopherPNG())
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")
}

func DecodeConfig

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

DecodeConfig возвращает цветовой режим и размеры изображения PNG без декодирования всего изображения.

func Encode

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

Encode записывает Image m в w в формате PNG. Любое изображение может быть закодировано, но изображения, которые не являются image.NRGBA, могут быть закодированы с потерями.

Пример

Код:

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)
}

тип CompressionLevel 1.4

CompressionLevel указывает уровень сжатия.

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

тип Encoder 1.4

Encoder настраивает кодирование изображений PNG.

type Encoder struct {
    CompressionLevel CompressionLevel

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

func (*Encoder) Encode 1.4

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

Encode записывает Image m в w в формате PNG.

тип EncoderBuffer 1.9

EncoderBuffer хранит буферы, используемые для кодирования изображений PNG.

type EncoderBuffer encoder

тип EncoderBufferPool 1.9

EncoderBufferPool — это интерфейс для получения и возврата временных экземпляров структуры EncoderBuffer. Это можно использовать для повторного использования буферов при кодировании нескольких изображений.

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

тип FormatError

FormatError сообщает о том, что входной данные не являются допустимым PNG.

type FormatError string

func (FormatError) Error

func (e FormatError) Error() string

тип UnsupportedError

UnsupportedError сообщает о том, что входные данные используют допустимую, но не реализованную функцию PNG.

type UnsupportedError string

func (UnsupportedError) Error

func (e UnsupportedError) Error() string

© Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
http://golang.org/pkg/image/png/

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API