golang.org/x/image/webp
| Language | Go |
|---|---|
| License | BSD-3-Clause |
| Repository | go.googlesource.com/image (mirror: github.com/golang/image) |
| Documentation | pkg.go.dev/golang.org/x/image/webp |
| Depends on | nothing (pure Go, no cgo) |
| Read / write | yes / no; lossy, lossless, alpha; no animation |
golang.org/x/image/webp is part of the Go project’s extended image packages. It decodes simple lossy, simple lossless and extended (with ALPH alpha) WebP files into standard image.Image values, and registers the format so image.Decode recognizes WebP.
It has no encoder and doesn’t decode animated WebP. To write WebP or read animations, use gen2brain/webp.
Installation#
Shell
go get golang.org/x/image/webp
Basic usage: convert WebP to PNG#
Go
package main
import (
"fmt"
"image/png"
"log"
"os"
"golang.org/x/image/webp"
)
func main() {
in, err := os.Open("in.webp")
if err != nil {
log.Fatal(err)
}
defer in.Close()
img, err := webp.Decode(in)
if err != nil {
log.Fatal(err)
}
b := img.Bounds()
fmt.Printf("%d x %d, %T\n", b.Dx(), b.Dy(), img) // *image.YCbCr (lossy), *image.NYCbCrA (lossy + alpha), *image.NRGBA (lossless)
out, err := os.Create("out.png")
if err != nil {
log.Fatal(err)
}
defer out.Close()
if err := png.Encode(out, img); err != nil {
log.Fatal(err)
}
}
How to get WebP dimensions without decoding#
DecodeConfig reads only the headers:
Go
f, err := os.Open("in.webp")
if err != nil {
log.Fatal(err)
}
defer f.Close()
cfg, err := webp.DecodeConfig(f)
if err != nil {
log.Fatal(err)
}
fmt.Println(cfg.Width, cfg.Height)
How to decode any image format, including WebP#
Import the package for its side effect; image.Decode then detects WebP by its RIFF....WEBP header:
Go
import (
"image"
_ "image/jpeg"
_ "image/png"
_ "golang.org/x/image/webp"
)
img, format, err := image.Decode(f) // format is "webp", "png" or "jpeg"
How to resize a WebP#
golang.org/x/image/draw has high-quality scalers:
Go
import (
"image"
"golang.org/x/image/draw"
)
src, err := webp.Decode(f)
if err != nil {
log.Fatal(err)
}
dst := image.NewRGBA(image.Rect(0, 0, src.Bounds().Dx()/2, src.Bounds().Dy()/2))
draw.CatmullRom.Scale(dst, dst.Bounds(), src, src.Bounds(), draw.Over, nil)
// encode dst with image/png or image/jpeg
Tips#
- An animated WebP returns an error; check with
gen2brain/webpif you need the frames. - Lossy images come back as
*image.YCbCr; draw them into an*image.RGBAonce if you need many pixel reads.