github.com/cellofellow/gopkg@v0.0.0-20140722061823-eec0544a62ad/image/png/png.go (about) 1 // Copyright 2014 <chaishushan{AT}gmail.com>. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package png implements a PNG image decoder and encoder. 6 // 7 // The PNG specification is at http://www.w3.org/TR/PNG/. 8 package png 9 10 import ( 11 "image" 12 "image/color" 13 "image/png" 14 "io" 15 16 image_ext "github.com/chai2010/gopkg/image" 17 "github.com/chai2010/gopkg/image/convert" 18 ) 19 20 const pngHeader = "\x89PNG\r\n\x1a\n" 21 22 // Options are the encoding and decoding parameters. 23 type Options struct { 24 ColorModel color.Model 25 } 26 27 // DecodeConfig returns the color model and dimensions of a PNG image 28 // without decoding the entire image. 29 func DecodeConfig(r io.Reader) (config image.Config, err error) { 30 return png.DecodeConfig(r) 31 } 32 33 // Decode reads a PNG image from r and returns it as an image.Image. 34 // The type of Image returned depends on the PNG contents. 35 func Decode(r io.Reader, opt *Options) (m image.Image, err error) { 36 if m, err = png.Decode(r); err != nil { 37 return 38 } 39 if opt != nil && opt.ColorModel != nil { 40 m = convert.ColorModel(m, opt.ColorModel) 41 } 42 return 43 } 44 45 // Encode writes the Image m to w in PNG format. 46 // Any Image may be encoded, but images that are not image.NRGBA 47 // might be encoded lossily. 48 func Encode(w io.Writer, m image.Image, opt *Options) error { 49 if opt != nil && opt.ColorModel != nil { 50 m = convert.ColorModel(m, opt.ColorModel) 51 } 52 return png.Encode(w, m) 53 } 54 55 func imageExtDecode(r io.Reader, opt interface{}) (image.Image, error) { 56 if opt, ok := opt.(*Options); ok { 57 return Decode(r, opt) 58 } else { 59 return Decode(r, nil) 60 } 61 } 62 63 func imageExtEncode(w io.Writer, m image.Image, opt interface{}) error { 64 if opt, ok := opt.(*Options); ok { 65 return Encode(w, m, opt) 66 } else { 67 return Encode(w, m, nil) 68 } 69 } 70 71 func init() { 72 image_ext.RegisterFormat(image_ext.Format{ 73 Name: "png", 74 Extensions: []string{".png"}, 75 Magics: []string{pngHeader}, 76 DecodeConfig: DecodeConfig, 77 Decode: imageExtDecode, 78 Encode: imageExtEncode, 79 }) 80 }