Documentation
¶
Overview ¶
Package webp provides a pure Go encoder and decoder for the WebP image format.
WebP is a modern image format developed by Google that provides superior lossless and lossy compression for images on the web. This package implements the full WebP specification without any CGo dependencies, making it fully portable and easy to cross-compile.
The package supports:
- Lossy decoding (VP8)
- Lossless decoding (VP8L)
- Alpha channel
- Lossy encoding (VP8)
- Lossless encoding (VP8L)
- Extended format (VP8X) with ICC, EXIF, XMP metadata
- Animation (ANIM/ANMF)
Basic usage for decoding:
img, err := webp.Decode(reader)
Basic usage for encoding:
err := webp.Encode(writer, img, &webp.Options{Quality: 80})
Package webp implements a decoder for the WebP image format.
WebP supports lossy (VP8), lossless (VP8L), and extended (VP8X) formats. This package registers itself with the standard library's image package so that image.Decode can transparently read WebP files.
Index ¶
Examples ¶
Constants ¶
const MaxDimension = 16383
MaxDimension is the maximum allowed width or height for a WebP image, in pixels. This matches libwebp's WEBP_MAX_DIMENSION constant. Images larger than 16383 pixels in either dimension cannot be represented in the WebP bitstream format.
Variables ¶
var ( ErrUnsupported = errors.New("webp: unsupported format") ErrNoFrames = errors.New("webp: no image frames found") )
Errors returned by the decoder.
Functions ¶
func Decode ¶
Decode reads a WebP image from r and returns it as an image.Image. For lossless images the returned type is *image.NRGBA. For lossy images the returned type is *image.YCbCr (when available) or *image.NRGBA.
Example ¶
package main
import (
"fmt"
"os"
"github.com/deepteams/webp"
)
func main() {
f, err := os.Open("testdata/red_4x4_lossy.webp")
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
img, err := webp.Decode(f)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("bounds: %v\n", img.Bounds())
}
Output: bounds: (0,0)-(4,4)
func DecodeConfig ¶
DecodeConfig returns the color model and dimensions of a WebP image without decoding the entire image.
Example ¶
package main
import (
"fmt"
"os"
"github.com/deepteams/webp"
)
func main() {
f, err := os.Open("testdata/blue_16x16_lossy.webp")
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
cfg, err := webp.DecodeConfig(f)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%dx%d\n", cfg.Width, cfg.Height)
}
Output: 16x16
func Encode ¶
Encode writes the image img to w in WebP format. If opts is nil, DefaultOptions() is used. Returns an error if opts contains invalid parameter values.
Example (Lossless) ¶
package main
import (
"bytes"
"fmt"
"image"
"image/color"
"github.com/deepteams/webp"
)
func main() {
img := image.NewNRGBA(image.Rect(0, 0, 8, 8))
for y := 0; y < 8; y++ {
for x := 0; x < 8; x++ {
img.SetNRGBA(x, y, color.NRGBA{R: 255, G: 0, B: 0, A: 255})
}
}
var buf bytes.Buffer
err := webp.Encode(&buf, img, &webp.EncoderOptions{
Lossless: true,
Quality: 75,
})
if err != nil {
fmt.Println(err)
return
}
if buf.Len() > 0 {
fmt.Println("ok")
}
}
Output: ok
Example (Lossy) ¶
package main
import (
"bytes"
"fmt"
"image"
"image/color"
"github.com/deepteams/webp"
)
func main() {
img := image.NewNRGBA(image.Rect(0, 0, 64, 64))
for y := 0; y < 64; y++ {
for x := 0; x < 64; x++ {
img.SetNRGBA(x, y, color.NRGBA{R: uint8(x * 4), G: uint8(y * 4), B: 128, A: 255})
}
}
var buf bytes.Buffer
err := webp.Encode(&buf, img, &webp.EncoderOptions{
Quality: 80,
Method: 4,
})
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("encoded %d bytes\n", buf.Len())
if buf.Len() > 0 {
fmt.Println("ok")
}
}
Output: encoded 208 bytes ok
Example (Roundtrip) ¶
package main
import (
"bytes"
"fmt"
"image"
"image/color"
"github.com/deepteams/webp"
)
func main() {
// Create a simple image.
original := image.NewNRGBA(image.Rect(0, 0, 16, 16))
for y := 0; y < 16; y++ {
for x := 0; x < 16; x++ {
original.SetNRGBA(x, y, color.NRGBA{R: 100, G: 150, B: 200, A: 255})
}
}
// Encode to WebP lossless.
var buf bytes.Buffer
err := webp.Encode(&buf, original, &webp.EncoderOptions{Lossless: true})
if err != nil {
fmt.Println(err)
return
}
// Decode back.
decoded, err := webp.Decode(&buf)
if err != nil {
fmt.Println(err)
return
}
// Verify pixel values match (lossless is exact).
p := decoded.(*image.NRGBA).NRGBAAt(0, 0)
fmt.Printf("R=%d G=%d B=%d A=%d\n", p.R, p.G, p.B, p.A)
}
Output: R=100 G=150 B=200 A=255
Types ¶
type EncoderOptions ¶
type EncoderOptions struct {
// Lossless enables VP8L lossless encoding.
// When false (default), VP8 lossy encoding is used.
Lossless bool
// Quality is the compression quality (0-100, default 75).
// For lossy: lower means smaller files with more artifacts.
// For lossless: controls the compression effort.
Quality float32
// Method controls encoding effort (0-6, default 4). Higher values
// produce smaller files at the cost of longer encoding times:
// 0 = fastest, least compression
// 4 = good trade-off between speed and quality (default)
// 6 = slowest, best compression
Method int
// Preset selects encoding parameters tuned for specific content types.
Preset Preset
// UseSharpYUV enables sharp (and slow) RGB->YUV conversion.
UseSharpYUV bool
// Exact preserves the RGB values under transparent areas. In lossless
// mode, transparent pixels' RGB are kept as-is instead of being zeroed.
// In lossy mode, it skips the transparent-area cleanup that normally
// flattens invisible pixels to reduce encoding cost. Note that lossy
// VP8 quantization will still modify pixel values regardless of this flag.
Exact bool
// TargetSize sets a target output size in bytes (0 = use quality instead).
TargetSize int
// TargetPSNR sets a target PSNR value (0 = disabled).
// When set (and TargetSize is 0), the encoder adjusts quality across
// multiple passes to converge toward this PSNR level.
// Matches C libwebp's WebPConfig::target_PSNR.
TargetPSNR float32
// Preprocessing selects preprocessing applied before/during encoding
// (lossy encoding only). This is a bitmask matching C libwebp's
// WebPConfig::preprocessing field:
// 0 = none
// 1 = segment smooth (applies a 3x3 majority-vote filter to the
// segment map, reducing noise in segment assignment)
// 2 = pseudo-random dithering on RGB->YUV conversion
// 3 = both segment smooth and dithering
// When bit 1 is set, ordered dithering noise is added to the rounding
// values during the RGB->YUV color space conversion. The amplitude
// decreases with quality: max dithering at q=0, 0.5 amplitude at q=100.
// This reduces banding artifacts at lower quality levels.
Preprocessing int
// SNSStrength controls spatial noise shaping strength (0-100, default 50).
// Higher values give more weight to low-frequency content, improving
// visual quality at the cost of higher distortion in high-frequency areas.
// Matches C libwebp's WebPConfig::sns_strength.
// The default value -1 (or any value < 0) is treated as 50.
SNSStrength int
// FilterStrength controls the strength of the deblocking loop filter
// (0-100, default 60). Higher values produce smoother edges but may
// blur details. Matches C libwebp's WebPConfig::filter_strength.
// The default value -1 (or any value < 0) is treated as 60.
FilterStrength int
// FilterSharpness controls the sharpness of the loop filter (0-7,
// default 0). Higher values sharpen the filter effect.
// Matches C libwebp's WebPConfig::filter_sharpness.
FilterSharpness int
// FilterType selects the loop filter type (0=simple, 1=strong, default 1).
// Strong filtering (1) also filters U/V channels.
// Matches C libwebp's WebPConfig::filter_type.
// The default value -1 (or any value < 0) is treated as 1 (strong).
FilterType int
// Partitions controls the number of token partitions (0-3, default 0).
// The actual number of partitions is 1 << Partitions (1, 2, 4, or 8).
// Matches C libwebp's WebPConfig::partitions.
Partitions int
// Segments controls the number of segments to use during encoding
// (1-4, default 4). Fewer segments speed up encoding at the cost of
// compression efficiency. Matches C libwebp's WebPConfig::segments.
// The default value -1 (or any value < 0) is treated as 4.
Segments int
// Pass controls the number of entropy-analysis passes (1-10, default 1).
// Higher values improve compression at the cost of encoding speed.
// Matches C libwebp's WebPConfig::pass.
// The default value -1 (or any value < 0) is treated as 1.
Pass int
// EmulateJpegSize, when true, tries to produce an output of similar
// size to a JPEG file of equivalent quality. This is a C libwebp
// compatibility field (WebPConfig::emulate_jpeg_size). The pure Go
// encoder does not implement this heuristic; the field is accepted
// for API compatibility but has no effect on output.
EmulateJpegSize bool
// QMin sets the minimum quantizer value (0-100, default 0).
// Must be <= QMax. Matches C libwebp's WebPConfig::qmin.
QMin int
// QMax sets the maximum quantizer value (0-100, default 100).
// Must be >= QMin. Matches C libwebp's WebPConfig::qmax.
// The default value -1 (or any value < 0) is treated as 100.
QMax int
// AlphaCompression selects the compression method for the alpha channel
// (lossy encoding only, ignored for lossless which handles alpha natively).
// Matches C libwebp's WebPConfig::alpha_compression.
// 0 = no compression (raw alpha bytes)
// 1 = VP8L lossless compression (default)
// The default value -1 (or any value < 0) is treated as 1 (lossless).
AlphaCompression int
// AlphaFiltering selects the predictive filtering method applied to the
// alpha plane before compression (lossy encoding only).
// Matches C libwebp's WebPConfig::alpha_filtering.
// 0 = none
// 1 = fast (quick heuristic, default)
// 2 = best (try all filters, pick smallest)
// The default value -1 (or any value < 0) is treated as 1 (fast).
AlphaFiltering int
// AlphaQuality controls the quality of the alpha channel encoding,
// independently of the main image quality (lossy encoding only).
// Range: 0-100. Values below 100 enable alpha level quantization
// (lossy alpha). Matches C libwebp's WebPConfig::alpha_quality.
// The default value -1 (or any value < 0) is treated as 100.
AlphaQuality int
// ICC holds an ICC color profile to embed in the output.
// When non-nil, the encoder uses VP8X extended format with the ICCP chunk.
ICC []byte
// EXIF holds EXIF metadata to embed in the output.
// When non-nil, the encoder uses VP8X extended format with the EXIF chunk.
EXIF []byte
// XMP holds XMP metadata to embed in the output.
// When non-nil, the encoder uses VP8X extended format with the XMP chunk.
XMP []byte
}
EncoderOptions controls WebP encoding parameters.
func DefaultOptions ¶
func DefaultOptions() *EncoderOptions
DefaultOptions returns encoding options with quality 75, lossy, method 4. All parameters match C libwebp's WebPConfigInit defaults. Sentinel values (-1) are used for fields where Go's zero value differs from the C default, ensuring that an uninitialized EncoderOptions{} produces sensible output.
Example ¶
package main
import (
"fmt"
"github.com/deepteams/webp"
)
func main() {
opts := webp.DefaultOptions()
fmt.Printf("quality: %.0f\n", opts.Quality)
fmt.Printf("lossless: %v\n", opts.Lossless)
fmt.Printf("method: %d\n", opts.Method)
}
Output: quality: 75 lossless: false method: 4
func OptionsForPreset ¶
func OptionsForPreset(preset Preset, quality float32) *EncoderOptions
OptionsForPreset returns encoding options tuned for the given preset and quality, matching C libwebp's WebPConfigPreset (config_enc.c:64-96).
Example ¶
package main
import (
"fmt"
"github.com/deepteams/webp"
)
func main() {
opts := webp.OptionsForPreset(webp.PresetPhoto, 90)
fmt.Printf("quality: %.0f\n", opts.Quality)
fmt.Printf("sns: %d\n", opts.SNSStrength)
}
Output: quality: 90 sns: 80
type Features ¶
type Features struct {
Width int // Image width in pixels.
Height int // Image height in pixels.
HasAlpha bool // True if the image contains an alpha channel.
HasAnimation bool // True if the image is animated (ANIM chunk present).
Format string // Container format: "lossy" (VP8), "lossless" (VP8L), or "extended" (VP8X).
LoopCount int // Animation loop count (0 = infinite). Only meaningful when HasAnimation is true.
FrameCount int // Number of frames (1 for still images).
}
Features describes a WebP file's properties, as returned by GetFeatures.
func GetFeatures ¶
GetFeatures reads WebP features (dimensions, format, alpha, animation) without decoding pixel data. It parses just the RIFF container and chunk headers, making it much cheaper than a full Decode.
Example ¶
package main
import (
"fmt"
"os"
"github.com/deepteams/webp"
)
func main() {
f, err := os.Open("testdata/red_4x4_lossless.webp")
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
feat, err := webp.GetFeatures(f)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("size: %dx%d\n", feat.Width, feat.Height)
fmt.Printf("format: %s\n", feat.Format)
fmt.Printf("alpha: %v\n", feat.HasAlpha)
}
Output: size: 4x4 format: lossless alpha: false
Directories
¶
| Path | Synopsis |
|---|---|
|
Package animation provides types and canvas logic for animated WebP images.
|
Package animation provides types and canvas logic for animated WebP images. |
|
cmd
|
|
|
gwebp
command
Command gwebp encodes and decodes WebP images from the command line.
|
Command gwebp encodes and decodes WebP images from the command line. |
|
internal
|
|
|
bitio
Package bitio provides bit-level I/O primitives for the WebP codec.
|
Package bitio provides bit-level I/O primitives for the WebP codec. |
|
container
Package container defines constants for the WebP/RIFF container format, including FourCC values, magic bytes, chunk IDs, and VP8/VP8L format constants.
|
Package container defines constants for the WebP/RIFF container format, including FourCC values, magic bytes, chunk IDs, and VP8/VP8L format constants. |
|
dsp
Package dsp provides low-level DSP routines for the WebP codec.
|
Package dsp provides low-level DSP routines for the WebP codec. |
|
lossy
Package lossy implements VP8 lossy codec constants, probability tables, and decoder/encoder primitives for WebP lossy compression.
|
Package lossy implements VP8 lossy codec constants, probability tables, and decoder/encoder primitives for WebP lossy compression. |
|
pool
Package pool provides bucketed sync.Pool instances for reducing allocations in hot paths.
|
Package pool provides bucketed sync.Pool instances for reducing allocations in hot paths. |
|
Package mux provides muxing and demuxing for the WebP RIFF container format.
|
Package mux provides muxing and demuxing for the WebP RIFF container format. |
|
Package sharpyuv implements sharp RGB to YUV420 conversion that minimizes chroma subsampling artifacts using iterative error diffusion.
|
Package sharpyuv implements sharp RGB to YUV420 conversion that minimizes chroma subsampling artifacts using iterative error diffusion. |