Documentation
¶
Overview ¶
Package decoder decodes WebP images (lossy, lossless, with alpha) with a pure Go implementation that produces the same pixels as libwebp.
Index ¶
- type Config
- type Decoder
- func (d *Decoder) Decode() (image.Image, error)
- func (d *Decoder) DecodeContext(ctx context.Context) (image.Image, error)
- func (d *Decoder) DecodeInto(dst *image.NRGBA) (*image.NRGBA, error)
- func (d *Decoder) DecodeIntoContext(ctx context.Context, dst *image.NRGBA) (*image.NRGBA, error)
- func (d *Decoder) DecodeNYCbCrA() (*image.NYCbCrA, error)
- func (d *Decoder) DecodeYCbCr() (*image.YCbCr, error)
- func (d *Decoder) GetFeatures() utils.BitstreamFeatures
- type Options
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// BypassFiltering skips the in-loop deblocking filter (lossy).
BypassFiltering bool
// NoFancyUpsampling uses point-sampled chroma upsampling (lossy).
NoFancyUpsampling bool
// UseCropping enables cropping to the CropWidth x CropHeight rectangle
// whose top-left corner is (CropLeft, CropTop).
UseCropping bool
CropLeft int
CropTop int
CropWidth int
CropHeight int
// UseScaling enables rescaling of the (cropped) picture to
// ScaledWidth x ScaledHeight.
UseScaling bool
ScaledWidth int
ScaledHeight int
// UseThreads decodes with helper goroutines from the process-wide
// budget of GOMAXPROCS-1 helpers shared by all concurrent Decode and
// Encode calls:
// - lossy pictures of at least 1024 macroblocks (about 512x512):
// one helper reconstructs, filters and emits batches of macroblock
// rows while the calling goroutine parses the next ones, and parses
// the prediction modes ahead when it has nothing else to do; when
// that helper is the slower stage, a second one takes over the
// conversion to RGBA;
// - lossy pictures with alpha whose alpha rows down to the bottom of
// the output region hold 256K pixels or more: another helper
// decodes the alpha plane ahead of the rows that need it;
// - lossless pictures of at least about 256K output pixels: the
// calling goroutine entropy-decodes while one helper applies the
// inverse transforms and writes the output rows (libwebp ignores
// use_threads for lossless pictures; this is a go-webp extension).
// Smaller pictures, or a call that finds no free helper slot, decode on
// the calling goroutine. The output is identical either way. A panic
// in a helper is re-raised on the calling goroutine.
UseThreads bool
// DitheringStrength in [0, 100] dithers the chroma of lossy pictures.
DitheringStrength int
// Flip mirrors the output vertically.
Flip bool
// AlphaDitheringStrength in [0, 100] smooths quantized alpha planes.
AlphaDitheringStrength int
}
Config is the decoding configuration built by Options.GetConfig. It mirrors libwebp's WebPDecoderOptions field for field (C int flags are bools). In v1 GetConfig returned the cgo type *C.WebPDecoderConfig; v2 returns this pure Go equivalent.
type Decoder ¶
type Decoder struct {
// contains filtered or unexported fields
}
Decoder stores information to decode picture
func NewDecoder ¶
NewDecoder return new decoder instance
func (*Decoder) DecodeContext ¶
DecodeContext is Decode with cancellation: once ctx is cancelled or its deadline has passed, decoding stops at the next batch of output rows (at most 16 rows of the frame; a lossless picture first reads its headers), and the error satisfies errors.Is(err, context.Canceled) (or context.DeadlineExceeded); its status code is VP8_STATUS_USER_ABORT. Helper goroutines (UseThreads) have exited when DecodeContext returns.
Example ¶
Bounding the time spent on one picture.
package main
import (
"bytes"
"context"
"fmt"
"os"
"time"
"github.com/kolesa-team/go-webp/v2/decoder"
)
func main() {
data, err := os.ReadFile("../test_data/images/m4_q75.webp")
if err != nil {
panic(err)
}
dec, err := decoder.NewDecoder(bytes.NewReader(data), nil)
if err != nil {
panic(err)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
img, err := dec.DecodeContext(ctx)
if err != nil {
panic(err) // errors.Is(err, context.DeadlineExceeded) after a minute
}
fmt.Println(img.Bounds().Size())
}
Output: (675,900)
func (*Decoder) DecodeInto ¶
DecodeInto decodes the picture like Decode, but into dst, so that a caller decoding many pictures can reuse one output buffer instead of allocating (and having the garbage collector reclaim) a new image per picture. It returns dst.
dst is treated as raw memory: its previous Rect and Stride are ignored. For an output of w x h pixels (after cropping and scaling), when cap(dst.Pix) >= 4*w*h the pixels are written to dst.Pix[:4*w*h] without allocating or clearing anything; otherwise a new buffer is allocated. On success dst.Pix is set to that w x h image (keeping the capacity of a reused buffer), dst.Stride to 4*w and dst.Rect to (0, 0)-(w, h); crop, scale and flip options apply as for Decode. Do not pass a SubImage: its Pix starts at the sub-image origin, so the decoded pixels would overwrite the rest of the parent image.
On error the dst fields are left unchanged, but the bytes of the memory dst.Pix refers to (up to its capacity) may have been partially overwritten.
The returned image is dst itself: decoding into dst again overwrites it. dst must not be used by other goroutines during the call. A nil dst makes DecodeInto behave like Decode (a new image is allocated).
Example ¶
Decoding many pictures into one reused image: after the buffer has grown to the largest picture, decoding allocates almost nothing.
package main
import (
"bytes"
"fmt"
"image"
"os"
"github.com/kolesa-team/go-webp/v2/decoder"
)
func main() {
var img *image.NRGBA // nil: the first decode allocates it
for _, name := range []string{"m4_q75.webp", "100x150_lossy.webp", "webp-logo-lossless.webp"} {
data, err := os.ReadFile("../test_data/images/" + name)
if err != nil {
panic(err)
}
dec, err := decoder.NewDecoder(bytes.NewReader(data), nil)
if err != nil {
panic(err)
}
// The result is img itself (or the image allocated for it):
// process it before the next decode overwrites it.
if img, err = dec.DecodeInto(img); err != nil {
panic(err)
}
fmt.Println(name, img.Bounds().Size())
}
}
Output: m4_q75.webp (675,900) 100x150_lossy.webp (100,150) webp-logo-lossless.webp (3000,2000)
func (*Decoder) DecodeIntoContext ¶
DecodeIntoContext is DecodeInto with cancellation, see DecodeContext.
func (*Decoder) DecodeNYCbCrA ¶
DecodeNYCbCrA is DecodeYCbCr for lossy pictures with or without alpha: the alpha plane (the decoded ALPH chunk, with AlphaDitheringStrength applied; all 0xff for an opaque picture) comes with the Y'CbCr 4:2:0 planes, 2.5 bytes per pixel in all. Lossless pictures are refused like by DecodeYCbCr.
func (*Decoder) DecodeYCbCr ¶
DecodeYCbCr decodes a lossy picture without alpha to its Y'CbCr 4:2:0 planes, without converting them to RGB: the output takes 1.5 bytes per pixel instead of 4, and decoding is faster. The planes hold the samples of the VP8 stream as they are (BT.601 "limited range"; libwebp's WebPDecodeYUV output), like the *image.YCbCr of golang.org/x/image/webp, so the colors that image.YCbCr's color model computes (full-range JFIF) differ slightly from the RGB that Decode returns, which also upsamples the chroma smoothly ("fancy upsampling") instead of repeating it.
Options: Crop (with its top-left corner rounded down to even coordinates, as for Decode), Flip (each plane is mirrored separately, like libwebp does for Y'CbCr output), BypassFiltering, DitheringStrength and UseThreads apply; NoFancyUpsampling has no effect. Scale is not supported (VP8_STATUS_INVALID_PARAM).
Pictures with alpha (use DecodeNYCbCrA), lossless pictures (they have no Y'CbCr form; use Decode) and animations are refused with VP8_STATUS_UNSUPPORTED_FEATURE: check GetFeatures first.
Example ¶
Decoding a lossy picture to its Y'CbCr planes, without the conversion to RGB.
package main
import (
"bytes"
"fmt"
"os"
"github.com/kolesa-team/go-webp/v2/decoder"
)
func main() {
data, err := os.ReadFile("../test_data/images/m4_q75.webp")
if err != nil {
panic(err)
}
dec, err := decoder.NewDecoder(bytes.NewReader(data), nil)
if err != nil {
panic(err)
}
if f := dec.GetFeatures(); f.HasAlpha {
panic("use DecodeNYCbCrA")
}
img, err := dec.DecodeYCbCr()
if err != nil {
panic(err)
}
fmt.Println(img.Bounds().Size(), img.SubsampleRatio, len(img.Y), len(img.Cb))
}
Output: (675,900) YCbCrSubsampleRatio420 607500 152100
func (*Decoder) GetFeatures ¶
func (d *Decoder) GetFeatures() utils.BitstreamFeatures
GetFeatures return information about picture: width, height ...
type Options ¶
type Options struct {
BypassFiltering bool
NoFancyUpsampling bool
Crop image.Rectangle
Scale image.Rectangle
UseThreads bool
Flip bool
DitheringStrength int
AlphaDitheringStrength int
}
Options specifies webp decoding parameters.
Crop uses libwebp's convention: Crop.Min is the top-left corner (crop_left, crop_top) and Crop.Max holds the crop WIDTH and HEIGHT (crop_width, crop_height), not the bottom-right corner. Cropping is enabled when both Crop.Max.X and Crop.Max.Y are positive. For lossy images the corner is rounded down to even coordinates, as libwebp does.
Scale.Max holds the output width and height; scaling is enabled when both are positive. Scaling is applied after cropping.