encoder

package
v2.0.3 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: MIT Imports: 18 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.

Documentation

Overview

Package encoder encodes images to WebP, lossy (VP8) or lossless (VP8L), with a pure Go implementation of libwebp's encoders.

Index

Constants

This section is empty.

Variables

View Source
var ErrReleased = errors.New("encoder: Encode called after Release")

ErrReleased is returned by Encode and EncodeContext when they are called after Release.

Functions

This section is empty.

Types

type Config

type Config struct {
	// Lossless selects lossless (VP8L) instead of lossy (VP8) coding.
	Lossless bool
	// Quality is in [0, 100]. For lossy coding it trades size for quality;
	// for lossless coding it is the compression effort.
	Quality float32
	// Method is the speed/quality trade-off in [0, 6] (0 = fastest).
	Method int
	// ImageHint is a hint about the picture type (lossless only).
	ImageHint ImageHint
	// TargetSize, if non-zero, is the desired output size in bytes (lossy).
	// As in libwebp it is only honored with Pass > 1.
	TargetSize int
	// TargetPSNR, if non-zero, is the desired PSNR in dB (lossy). As in
	// libwebp it is only honored with Pass > 1.
	TargetPSNR float32
	// Segments is the number of segments in [1, 4] (lossy).
	Segments int
	// SNSStrength is the spatial noise shaping strength in [0, 100] (lossy).
	SNSStrength int
	// FilterStrength is the loop filter strength in [0, 100] (lossy).
	FilterStrength int
	// FilterSharpness is the loop filter sharpness in [0, 7] (lossy).
	FilterSharpness int
	// FilterType is 0 for the simple and 1 for the strong loop filter (lossy).
	FilterType int
	// Autofilter adjusts the filter strength automatically (lossy).
	Autofilter bool
	// AlphaCompression is 0 for raw and 1 for lossless-compressed alpha.
	AlphaCompression int
	// AlphaFiltering is 0 (none), 1 (fast) or 2 (best) alpha prediction filtering.
	AlphaFiltering int
	// AlphaQuality in [0, 100]: below 100 the alpha plane is quantized.
	AlphaQuality int
	// Pass is the number of entropy-analysis passes in [1, 10] (lossy).
	Pass int
	// ShowCompressed is accepted for compatibility; it has no effect.
	ShowCompressed bool
	// Preprocessing in [0, 7]: bit 0 segment smoothing, bit 1 dithering,
	// bit 2 sharp YUV conversion (lossy).
	Preprocessing int
	// Partitions is log2 of the number of token partitions in [0, 3]
	// (lossy). As in libwebp it is ignored (a single partition is written)
	// for Method >= 3 unless LowMemory is set.
	Partitions int
	// PartitionLimit in [0, 100] allows quality degradation to fit the
	// 512k limit on the first partition (lossy).
	PartitionLimit int
	// EmulateJPEGSize maps the quality like a JPEG encoder would (lossy).
	EmulateJPEGSize bool
	// ThreadLevel allows the encoder to use helper goroutines from the
	// process-wide budget of GOMAXPROCS-1 helpers shared by all concurrent
	// Encode and Decode calls:
	//   - lossy: the analysis pass runs in row bands (pictures of at least
	//     384 macroblocks, 1024 at methods 0-1), the macroblock rows are
	//     coded as a wavefront on up to 8 goroutines when the picture is
	//     large enough to pay for it (about 0.3 MP at methods 3-6, several
	//     MP at methods 0-2), and the compressed alpha plane of a
	//     transparent picture (64K pixels or more) is coded while the VP8
	//     frame is;
	//   - lossless and compressed alpha (256K pixels or more): the
	//     hash-chain match search, the predictor search (methods 0-4) and
	//     the histogram remap are split among helpers, and level 9 codes at
	//     most two candidate configurations at a time (one above 8 MP).
	// When no helper slot is free the calling goroutine does the work. The
	// output is byte-identical with or without ThreadLevel and for any
	// budget. ThreadLevel lowers latency at some extra CPU cost; servers
	// that already encode concurrently may prefer to leave it off.
	ThreadLevel bool
	// LowMemory reduces memory usage at some cost in speed or size
	// (lossless). For lossy coding it only re-enables Partitions at
	// Method >= 3, as libwebp's low_memory does.
	LowMemory bool
	// NearLossless in [0, 100] enables near-lossless preprocessing (100 = off).
	NearLossless int
	// Exact preserves the RGB values under fully transparent pixels.
	Exact bool
	// UseDeltaPalette is accepted for compatibility; it has no effect.
	UseDeltaPalette bool
	// UseSharpYUV uses the slower but sharper RGB->YUV conversion (lossy).
	UseSharpYUV bool
}

Config is the validated encoding configuration built by Options.GetConfig. It mirrors libwebp's WebPConfig field for field (C int flags are bools). In v1 GetConfig returned the cgo type *C.WebPConfig; v2 returns this pure Go equivalent.

type Encoder

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

Encoder stores information to encode image

func NewEncoder

func NewEncoder(src image.Image, options *Options) (e *Encoder, err error)

NewEncoder return new encoder instance

func (*Encoder) Encode

func (e *Encoder) Encode(w io.Writer) error

Encode picture and flush to io.Writer

func (*Encoder) EncodeContext

func (e *Encoder) EncodeContext(ctx context.Context, w io.Writer) error

EncodeContext is Encode, but gives up when ctx is done: the encoders check ctx about once per macroblock row (lossy) and between their passes and search rows (lossless), stop together with their helper goroutines, and EncodeContext returns ctx.Err() (not wrapped). Nothing is written to w unless ctx is still not done once the file is complete. Converting the source picture, which NewEncoder does, is not covered.

func (*Encoder) Release

func (e *Encoder) Release()

Release hands the Encoder's copy of its source picture back to internal pools, so that later encodes can reuse the memory. Encode and EncodeContext return ErrReleased afterwards. Release waits for the encodes in progress on other goroutines; calling it again does nothing.

Calling Release is optional: otherwise the garbage collector reclaims the copy like any other memory once the Encoder is unreachable, as with v1, which had no Release; only Release lets later encodes reuse it.

type EncodingPreset

type EncodingPreset int

EncodingPreset using Preset

const (
	PresetDefault EncodingPreset = iota
	PresetPicture
	PresetPhoto
	PresetDrawing
	PresetIcon
	PresetText
)

Default libwebp presets

type ImageHint

type ImageHint int

ImageHint hint of picture

const (
	HintDefault ImageHint = iota
	HintPicture
	HintPhoto
	HintGraph
	HintLast
)

Default libwebp image hints

type Options

type Options struct {
	Lossless         bool
	Quality          float32
	Method           int
	ImageHint        ImageHint
	TargetSize       int
	TargetPsnr       float32
	Segments         int
	SnsStrength      int
	FilterStrength   int
	FilterSharpness  int
	FilterType       int
	Autofilter       bool
	AlphaCompression int
	AlphaFiltering   int

	Pass int
	// Disabled for compatibility with old version libwebp
	// QMin             int
	// QMax             int
	ShowCompressed  bool
	Preprocessing   int
	Partitions      int
	PartitionLimit  int
	EmulateJpegSize bool
	ThreadLevel     bool
	LowMemory       bool
	NearLossless    int
	Exact           int
	UseDeltaPalette bool
	UseSharpYuv     bool
	// contains filtered or unexported fields
}

Options specifies webp encoding parameters. The field semantics are those of libwebp's WebPConfig.

func NewLosslessEncoderOptions

func NewLosslessEncoderOptions(preset EncodingPreset, level int) (options *Options, err error)

NewLosslessEncoderOptions build lossless encoding options

func NewLossyEncoderOptions

func NewLossyEncoderOptions(preset EncodingPreset, quality float32) (options *Options, err error)

NewLossyEncoderOptions build lossy encoding options

func (*Options) GetConfig

func (o *Options) GetConfig() (*Config, error)

GetConfig builds and validates the encoder configuration (the equivalent of libwebp's WebPConfig after WebPValidateConfig). A nil *Options yields the lossless preset of level 0.

Jump to

Keyboard shortcuts

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