package codec import ( "bytes" "github.com/foobaz/lossypng/lossypng" "image" "image/png" "io" ) type PNGCoder struct{} const qMax = 20 func (coder PNGCoder) Decode(r io.Reader) (image.Image, error) { i, err := png.Decode(r) if err != nil { return nil, err } return i, nil } func (coder PNGCoder) Encode(i image.Image, quality int) (buf bytes.Buffer, err error) { c := lossypng.Compress(i, 2, qualityFactor(quality)) err = png.Encode(&buf, c) return buf, err } // qualityFactor normalizes the PNG quality factor from a max of 20, where 0 is // no conversion. func qualityFactor(q int) int { f := q / 100 return qMax - (f * qMax) }