From d42a5861d4b205c7535ecea2a17caafcbe539d54 Mon Sep 17 00:00:00 2001 From: Sander Schobers Date: Thu, 11 Feb 2021 20:33:06 +0100 Subject: [PATCH] Added support for JPEG encoding/decoding in utio. --- utio/imager.go | 18 ++++++++++++++++++ utio/jpeg.go | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ utio/png.go | 14 +++----------- 3 files changed, 71 insertions(+), 11 deletions(-) create mode 100644 utio/imager.go create mode 100644 utio/jpeg.go diff --git a/utio/imager.go b/utio/imager.go new file mode 100644 index 0000000..a7d6641 --- /dev/null +++ b/utio/imager.go @@ -0,0 +1,18 @@ +package utio + +import "image" + +// Imager describes a image encoder/decoder. +type Imager interface { + Encoder + Decoder + Image() image.Image +} + +type imager struct { + m image.Image +} + +func (i *imager) Image() image.Image { + return i.m +} diff --git a/utio/jpeg.go b/utio/jpeg.go new file mode 100644 index 0000000..8f5346f --- /dev/null +++ b/utio/jpeg.go @@ -0,0 +1,50 @@ +package utio + +import ( + "image" + "image/jpeg" + "io" +) + +// JPEG creates a JPEG encoder/decoder for m, m is only required for encoding. +func JPEG(m image.Image) Imager { + return JPEGOpts(m, 95) +} + +func JPEGOpts(m image.Image, quality int) Imager { + return &jpeger{imager{m}, quality} +} + +type jpeger struct { + imager + + quality int +} + +func (j *jpeger) Encode(w io.Writer) error { + return jpeg.Encode(w, j.m, &jpeg.Options{Quality: j.quality}) +} + +func (j *jpeger) Decode(r io.Reader) error { + var m, err = jpeg.Decode(r) + if nil != err { + return err + } + j.m = m + return nil +} + +// LoadJPEG loads a JPEG image from the supplied path. +func LoadJPEG(path string) (image.Image, error) { + var j = JPEG(nil) + var err = DecodeFile(path, j) + if nil != err { + return nil, err + } + return j.Image(), nil +} + +// SaveJPEG writes an image as JPEG to the supplied path. +func SaveJPEG(path string, m image.Image) error { + return EncodeFile(path, JPEG(m)) +} diff --git a/utio/png.go b/utio/png.go index 83ba231..61f668b 100644 --- a/utio/png.go +++ b/utio/png.go @@ -7,19 +7,15 @@ import ( ) // PNGer describes a PNG encoder/decoder. -type PNGer interface { - Encoder - Decoder - Image() image.Image -} +type PNGer Imager // PNG creates a PNG encoder/decoder for m, m is only required for encoding. func PNG(m image.Image) PNGer { - return &pnger{m} + return &pnger{imager{m}} } type pnger struct { - m image.Image + imager } func (p *pnger) Encode(w io.Writer) error { @@ -35,10 +31,6 @@ func (p *pnger) Decode(r io.Reader) error { return nil } -func (p *pnger) Image() image.Image { - return p.m -} - // LoadPNG loads a PNG image from the supplied path. func LoadPNG(path string) (image.Image, error) { var p = PNG(nil)