From e2ef9fd86ddb97647f7aca80868a5c20824f20f8 Mon Sep 17 00:00:00 2001 From: JP Hastings-Spital Date: Fri, 23 Sep 2022 23:42:59 +0100 Subject: [PATCH] Adds compatibility with the std image lib Adding `import _ "github.com/kolesa-team/go-webp"` to a file will allow `image.Decode` to automatically detect and decode WebP files. Repicates the approach used in [golang.org/x/image/webp](https://cs.opensource.google/go/x/image/+/master:webp/decode.go). --- webp.go | 23 +++++++++++++++++++++++ webp/webp.go | 21 +++++++++++++++++++-- 2 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 webp.go diff --git a/webp.go b/webp.go new file mode 100644 index 0000000..933b645 --- /dev/null +++ b/webp.go @@ -0,0 +1,23 @@ +package webp + +// Importing this package allows decoding of webp image files using the standard library's image.Decode. +// It will clash with the golang.org/x/image/webp package + +import ( + "image" + "io" + + "github.com/kolesa-team/go-webp/webp" +) + +func init() { + image.RegisterFormat("webp", "RIFF????WEBPVP8", quickDecode, quickDecodeConfig) +} + +func quickDecode(r io.Reader) (image.Image, error) { + return webp.Decode(r, nil) +} + +func quickDecodeConfig(r io.Reader) (image.Config, error) { + return webp.DecodeConfig(r, nil) +} diff --git a/webp/webp.go b/webp/webp.go index 0f9c87d..9c3bf34 100644 --- a/webp/webp.go +++ b/webp/webp.go @@ -22,10 +22,12 @@ package webp import ( - "github.com/kolesa-team/go-webp/decoder" - "github.com/kolesa-team/go-webp/encoder" "image" + "image/color" "io" + + "github.com/kolesa-team/go-webp/decoder" + "github.com/kolesa-team/go-webp/encoder" ) // Decode picture from reader @@ -37,6 +39,21 @@ func Decode(r io.Reader, options *decoder.Options) (image.Image, error) { } } +// DecodeConfig extracts simple metadata without decoding the image +func DecodeConfig(r io.Reader, options *decoder.Options) (image.Config, error) { + dec, err := decoder.NewDecoder(r, options) + if err != nil { + return image.Config{}, err + } + + feat := dec.GetFeatures() + return image.Config{ + ColorModel: color.NRGBAModel, + Width: feat.Width, + Height: feat.Height, + }, nil +} + // Encode encode picture and write to io.Writer func Encode(w io.Writer, src image.Image, options *encoder.Options) error { if enc, err := encoder.NewEncoder(src, options); err != nil {