gif

package module
v0.0.0-...-1fbd2e6 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2022 License: BSD-2-Clause Imports: 13 Imported by: 1

README

gifx is a drop-in replacement fork of the standard image/gif package with improved support for animated GIF files.

  • Encode and decode images one at a time to reduce peak memory usage.
  • Extract the first image from an animation without parsing the entire file.
  • Store and retrieve comment and plain text extension data.
  • Optimize output file size by only storing inter-frame changes.

Original code copyright 2013 The Go Authors. No changes have been made to the original reader.go and writer.go source files as forked from Go 1.18.

Decode example

Extract each frame from an animated GIF and save them to disk. Each image is eligible for GC before the next frame is decoded.

f, _ := os.Open("tmp.gif")
defer f.Close()
dec := gif.NewDecoder(f)
dec.ReadHeader()
i := 0
for {
    if blk, err := dec.ReadBlock(); err == io.EOF {
        break
    } else if frm, ok := blk.(*gif.Frame); ok {
        f, _ := os.Create(fmt.Sprintf("tmp%d.gif", i))
        gif.Encode(f, frm.Image, nil)
        f.Close()
        i++
    }
}

Encode example

Create a random 100 frame greyscale animated GIF using only a single allocated image.Paletted struct.

f, _ := os.Create("tmp.gif")
defer f.Close()
enc := gif.NewEncoder(f)
pal := make(color.Palette, 0x100)
for i := range pal {
    pal[i] = color.Gray{Y: uint8(i)}
}
enc.WriteHeader(image.Config{Width: 100, Height: 100, ColorModel: pal}, 0)
pm := image.NewPaletted(image.Rect(0, 0, 100, 100), pal)
for i := 0; i < 100; i++ {
    rand.Read(pm.Pix)
    enc.WriteFrame(&gif.Frame{Image: pm})
}
enc.WriteTrailer()
enc.Flush()

Optimize example

Optimize each frame by replacing unchanged pixels with the transparent palette entry and optionally cropping the image.

pal[0xff] = color.Transparent
opt := gif.NewOptimizer(0xff)
pm := image.NewPaletted(image.Rect(0, 0, 100, 100), pal)
for {
    // draw frame
    pm, _ := opt.Optimize(pm)
    _ = enc.WriteFrame(&gif.Frame{Image: pm})
}

Documentation

Overview

Package gif implements a GIF image decoder and encoder.

The GIF specification is at https://www.w3.org/Graphics/GIF/spec-gif89a.txt.

Index

Examples

Constants

View Source
const (
	DisposalNone       = 0x01
	DisposalBackground = 0x02
	DisposalPrevious   = 0x03
)

Disposal Methods.

Variables

This section is empty.

Functions

func Decode

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

Decode reads a GIF image from r and returns the first embedded image as an image.Image.

func DecodeConfig

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

DecodeConfig returns the global color model and dimensions of a GIF image without decoding the entire image.

func Encode

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

Encode writes the Image m to w in GIF format.

func EncodeAll

func EncodeAll(w io.Writer, g *GIF) error

EncodeAll writes the images in g to w in GIF format with the given loop count and delay between frames.

func OptimizeAll

func OptimizeAll(pms []*image.Paletted, transparentIndex uint8) error

OptimizeAll takes a slice of images and replaces unchanged pixels with the transparent palette index. Each image is then cropped to omit unchanged regions where possible.

func WithDrawer

func WithDrawer(d draw.Drawer) option

func WithNumColors

func WithNumColors(n int) option

func WithQuantizer

func WithQuantizer(q draw.Quantizer) option

Types

type ApplicationNetscape

type ApplicationNetscape struct {
	LoopCount int      // Number of times an animation will be restarted during display.
	SubBlocks [][]byte // Optional sub-blocks of arbitrary data.
}

type Comment

type Comment struct {
	Strings []string // Comments, up to 255 ASCII characters per string.
}

type Decoder

type Decoder = decoder

func NewDecoder

func NewDecoder(r io.Reader) *Decoder
Example
f, _ := os.Open("tmp.gif")
defer f.Close()

dec := gif.NewDecoder(f)
_, _ = dec.ReadHeader()

i := 0
for {
	if blk, err := dec.ReadBlock(); err == io.EOF {
		break
	} else if frm, ok := blk.(*gif.Frame); ok {
		f, _ := os.Create(fmt.Sprintf("tmp%d.gif", i))
		_ = gif.Encode(f, frm.Image, nil)
		_ = f.Close()
		i++
	}
}
Output:

func (*Decoder) Decode

func (d *Decoder) Decode() (*GIF, error)

func (*Decoder) DecodeConfig

func (d *Decoder) DecodeConfig() (image.Config, error)

func (*Decoder) DecodeFirst

func (d *Decoder) DecodeFirst() (image.Image, error)

func (*Decoder) ReadBlock

func (d *Decoder) ReadBlock() (interface{}, error)

func (*Decoder) ReadHeader

func (d *Decoder) ReadHeader() (*Header, error)

type Encoder

type Encoder = encoder

func NewEncoder

func NewEncoder(w io.Writer) *Encoder
Example
f, _ := os.Create("tmp.gif")
defer f.Close()

enc := gif.NewEncoder(f)
pal := make(color.Palette, 0x100)
for i := range pal {
	pal[i] = color.Gray{Y: uint8(i)}
}

_ = enc.WriteHeader(image.Config{Width: 100, Height: 100, ColorModel: pal}, 0)

pm := image.NewPaletted(image.Rect(0, 0, 100, 100), pal)
for i := 0; i < 100; i++ {
	rand.Read(pm.Pix)
	_ = enc.WriteFrame(&gif.Frame{Image: pm})
}

_ = enc.WriteTrailer()
_ = enc.Flush()
Output:

func (*Encoder) Encode

func (e *Encoder) Encode(g *GIF) error

func (*Encoder) EncodeImage

func (e *Encoder) EncodeImage(m image.Image, o ...option) error

func (*Encoder) Flush

func (e *Encoder) Flush() error

func (*Encoder) WriteApplicationNetscape

func (e *Encoder) WriteApplicationNetscape(an *ApplicationNetscape) error

func (*Encoder) WriteComment

func (e *Encoder) WriteComment(c *Comment) error

func (*Encoder) WriteFrame

func (e *Encoder) WriteFrame(f *Frame) error

func (*Encoder) WriteHeader

func (e *Encoder) WriteHeader(cfg image.Config, backgroundIndex byte) error

func (*Encoder) WritePlainText

func (e *Encoder) WritePlainText(pt *PlainText) error

func (*Encoder) WriteTrailer

func (e *Encoder) WriteTrailer() error

func (*Encoder) WriteUnknownApplication

func (e *Encoder) WriteUnknownApplication(ua *UnknownApplication) error

func (*Encoder) WriteUnknownExtension

func (e *Encoder) WriteUnknownExtension(ue *UnknownExtension) error

type Frame

type Frame struct {
	Image          *image.Paletted // Paletted image.
	DelayTime      time.Duration   // Delay time rounded to 100ths of a second.
	DisposalMethod byte            // Disposal method, one of DisposalNone, DisposalBackground, DisposalPrevious.
}

type GIF

type GIF struct {
	Image []*image.Paletted // The successive images.
	Delay []int             // The successive delay times, one per frame, in 100ths of a second.
	// LoopCount controls the number of times an animation will be
	// restarted during display.
	// A LoopCount of 0 means to loop forever.
	// A LoopCount of -1 means to show each frame only once.
	// Otherwise, the animation is looped LoopCount+1 times.
	LoopCount int
	// Disposal is the successive disposal methods, one per frame. For
	// backwards compatibility, a nil Disposal is valid to pass to EncodeAll,
	// and implies that each frame's disposal method is 0 (no disposal
	// specified).
	Disposal []byte
	// Config is the global color table (palette), width and height. A nil or
	// empty-color.Palette Config.ColorModel means that each frame has its own
	// color table and there is no global color table. Each frame's bounds must
	// be within the rectangle defined by the two points (0, 0) and
	// (Config.Width, Config.Height).
	//
	// For backwards compatibility, a zero-valued Config is valid to pass to
	// EncodeAll, and implies that the overall GIF's width and height equals
	// the first frame's bounds' Rectangle.Max point.
	Config image.Config
	// BackgroundIndex is the background index in the global color table, for
	// use with the DisposalBackground disposal method.
	BackgroundIndex byte
}

GIF represents the possibly multiple images stored in a GIF file.

func DecodeAll

func DecodeAll(r io.Reader) (*GIF, error)

DecodeAll reads a GIF image from r and returns the sequential frames and timing information.

type Header struct {
	Version         string       // GIF version, either GIF87a or GIF89a.
	Config          image.Config // Global color table (palette), width and height.
	BackgroundIndex byte         // Background index in the global color table, for use with the DisposalBackground disposal method.
}

type Optimizer

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

func NewOptimizer

func NewOptimizer(transparentIndex uint8) *Optimizer

NewOptimizer returns a new Optimizer with the given transparent palette index.

func (*Optimizer) Optimize

func (o *Optimizer) Optimize(pm *image.Paletted) (*image.Paletted, error)

Optimize compares the given image with the previous frame and replaces identical pixels with the transparent palette index. The smallest possible sub-image containing all changed pixels is returned. The first image passed cannot be optimized and is only used to initialize the internal image buffer.

type Options

type Options struct {
	// NumColors is the maximum number of colors used in the image.
	// It ranges from 1 to 256.
	NumColors int

	// Quantizer is used to produce a palette with size NumColors.
	// palette.Plan9 is used in place of a nil Quantizer.
	Quantizer draw.Quantizer

	// Drawer is used to convert the source image to the desired palette.
	// draw.FloydSteinberg is used in place of a nil Drawer.
	Drawer draw.Drawer
}

Options are the encoding parameters.

type PlainText

type PlainText struct {
	TextGridLeftPosition     uint16
	TextGridTopPosition      uint16
	TextGridWidth            uint16
	TextGridHeight           uint16
	CharacterCellWidth       byte
	CharacterCellHeight      byte
	TextForegroundColorIndex byte
	TextBackgroundColorIndex byte
	Strings                  []string      // Text, up to 255 ASCII characters per string.
	DelayTime                time.Duration // Delay time rounded to 100ths of a second.
	DisposalMethod           byte          // Disposal method, one of DisposalNone, DisposalBackground, DisposalPrevious.
}

type UnknownApplication

type UnknownApplication struct {
	Identifier string   // Identifier string of the application.
	SubBlocks  [][]byte // Optional sub-blocks of arbitrary data.
}

type UnknownExtension

type UnknownExtension struct {
	Label     byte
	SubBlocks [][]byte // Optional sub-blocks of arbitrary data.
}

Directories

Path Synopsis
demo

Jump to

Keyboard shortcuts

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