Added support for JPEG encoding/decoding in utio.

This commit is contained in:
Sander Schobers 2021-02-11 20:33:06 +01:00
parent c60d1b2724
commit d42a5861d4
3 changed files with 71 additions and 11 deletions

18
utio/imager.go Normal file
View File

@ -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
}

50
utio/jpeg.go Normal file
View File

@ -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))
}

View File

@ -7,19 +7,15 @@ import (
) )
// PNGer describes a PNG encoder/decoder. // PNGer describes a PNG encoder/decoder.
type PNGer interface { type PNGer Imager
Encoder
Decoder
Image() image.Image
}
// PNG creates a PNG encoder/decoder for m, m is only required for encoding. // PNG creates a PNG encoder/decoder for m, m is only required for encoding.
func PNG(m image.Image) PNGer { func PNG(m image.Image) PNGer {
return &pnger{m} return &pnger{imager{m}}
} }
type pnger struct { type pnger struct {
m image.Image imager
} }
func (p *pnger) Encode(w io.Writer) error { func (p *pnger) Encode(w io.Writer) error {
@ -35,10 +31,6 @@ func (p *pnger) Decode(r io.Reader) error {
return nil return nil
} }
func (p *pnger) Image() image.Image {
return p.m
}
// LoadPNG loads a PNG image from the supplied path. // LoadPNG loads a PNG image from the supplied path.
func LoadPNG(path string) (image.Image, error) { func LoadPNG(path string) (image.Image, error) {
var p = PNG(nil) var p = PNG(nil)