helpers.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. package imaging
  2. import (
  3. "errors"
  4. "image"
  5. "image/color"
  6. "image/draw"
  7. "image/gif"
  8. "image/jpeg"
  9. "image/png"
  10. "io"
  11. "os"
  12. "path/filepath"
  13. "strings"
  14. "golang.org/x/image/bmp"
  15. "golang.org/x/image/tiff"
  16. )
  17. // Format is an image file format.
  18. type Format int
  19. // Image file formats.
  20. const (
  21. JPEG Format = iota
  22. PNG
  23. GIF
  24. TIFF
  25. BMP
  26. )
  27. func (f Format) String() string {
  28. switch f {
  29. case JPEG:
  30. return "JPEG"
  31. case PNG:
  32. return "PNG"
  33. case GIF:
  34. return "GIF"
  35. case TIFF:
  36. return "TIFF"
  37. case BMP:
  38. return "BMP"
  39. default:
  40. return "Unsupported"
  41. }
  42. }
  43. var (
  44. // ErrUnsupportedFormat means the given image format (or file extension) is unsupported.
  45. ErrUnsupportedFormat = errors.New("imaging: unsupported image format")
  46. )
  47. type fileSystem interface {
  48. Create(string) (io.WriteCloser, error)
  49. Open(string) (io.ReadCloser, error)
  50. }
  51. type localFS struct{}
  52. func (localFS) Create(name string) (io.WriteCloser, error) { return os.Create(name) }
  53. func (localFS) Open(name string) (io.ReadCloser, error) { return os.Open(name) }
  54. var fs fileSystem = localFS{}
  55. // Decode reads an image from r.
  56. func Decode(r io.Reader) (image.Image, error) {
  57. img, _, err := image.Decode(r)
  58. return img, err
  59. }
  60. // Open loads an image from file
  61. func Open(filename string) (image.Image, error) {
  62. file, err := fs.Open(filename)
  63. if err != nil {
  64. return nil, err
  65. }
  66. defer file.Close()
  67. return Decode(file)
  68. }
  69. type encodeConfig struct {
  70. jpegQuality int
  71. gifNumColors int
  72. gifQuantizer draw.Quantizer
  73. gifDrawer draw.Drawer
  74. pngCompressionLevel png.CompressionLevel
  75. }
  76. var defaultEncodeConfig = encodeConfig{
  77. jpegQuality: 95,
  78. gifNumColors: 256,
  79. gifQuantizer: nil,
  80. gifDrawer: nil,
  81. pngCompressionLevel: png.DefaultCompression,
  82. }
  83. // EncodeOption sets an optional parameter for the Encode and Save functions.
  84. type EncodeOption func(*encodeConfig)
  85. // JPEGQuality returns an EncodeOption that sets the output JPEG quality.
  86. // Quality ranges from 1 to 100 inclusive, higher is better. Default is 95.
  87. func JPEGQuality(quality int) EncodeOption {
  88. return func(c *encodeConfig) {
  89. c.jpegQuality = quality
  90. }
  91. }
  92. // GIFNumColors returns an EncodeOption that sets the maximum number of colors
  93. // used in the GIF-encoded image. It ranges from 1 to 256. Default is 256.
  94. func GIFNumColors(numColors int) EncodeOption {
  95. return func(c *encodeConfig) {
  96. c.gifNumColors = numColors
  97. }
  98. }
  99. // GIFQuantizer returns an EncodeOption that sets the quantizer that is used to produce
  100. // a palette of the GIF-encoded image.
  101. func GIFQuantizer(quantizer draw.Quantizer) EncodeOption {
  102. return func(c *encodeConfig) {
  103. c.gifQuantizer = quantizer
  104. }
  105. }
  106. // GIFDrawer returns an EncodeOption that sets the drawer that is used to convert
  107. // the source image to the desired palette of the GIF-encoded image.
  108. func GIFDrawer(drawer draw.Drawer) EncodeOption {
  109. return func(c *encodeConfig) {
  110. c.gifDrawer = drawer
  111. }
  112. }
  113. // PNGCompressionLevel returns an EncodeOption that sets the compression level
  114. // of the PNG-encoded image. Default is png.DefaultCompression.
  115. func PNGCompressionLevel(level png.CompressionLevel) EncodeOption {
  116. return func(c *encodeConfig) {
  117. c.pngCompressionLevel = level
  118. }
  119. }
  120. // Encode writes the image img to w in the specified format (JPEG, PNG, GIF, TIFF or BMP).
  121. func Encode(w io.Writer, img image.Image, format Format, opts ...EncodeOption) error {
  122. cfg := defaultEncodeConfig
  123. for _, option := range opts {
  124. option(&cfg)
  125. }
  126. var err error
  127. switch format {
  128. case JPEG:
  129. var rgba *image.RGBA
  130. if nrgba, ok := img.(*image.NRGBA); ok {
  131. if nrgba.Opaque() {
  132. rgba = &image.RGBA{
  133. Pix: nrgba.Pix,
  134. Stride: nrgba.Stride,
  135. Rect: nrgba.Rect,
  136. }
  137. }
  138. }
  139. if rgba != nil {
  140. err = jpeg.Encode(w, rgba, &jpeg.Options{Quality: cfg.jpegQuality})
  141. } else {
  142. err = jpeg.Encode(w, img, &jpeg.Options{Quality: cfg.jpegQuality})
  143. }
  144. case PNG:
  145. enc := png.Encoder{CompressionLevel: cfg.pngCompressionLevel}
  146. err = enc.Encode(w, img)
  147. case GIF:
  148. err = gif.Encode(w, img, &gif.Options{
  149. NumColors: cfg.gifNumColors,
  150. Quantizer: cfg.gifQuantizer,
  151. Drawer: cfg.gifDrawer,
  152. })
  153. case TIFF:
  154. err = tiff.Encode(w, img, &tiff.Options{Compression: tiff.Deflate, Predictor: true})
  155. case BMP:
  156. err = bmp.Encode(w, img)
  157. default:
  158. err = ErrUnsupportedFormat
  159. }
  160. return err
  161. }
  162. // Save saves the image to file with the specified filename.
  163. // The format is determined from the filename extension: "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported.
  164. //
  165. // Examples:
  166. //
  167. // // Save the image as PNG.
  168. // err := imaging.Save(img, "out.png")
  169. //
  170. // // Save the image as JPEG with optional quality parameter set to 80.
  171. // err := imaging.Save(img, "out.jpg", imaging.JPEGQuality(80))
  172. //
  173. func Save(img image.Image, filename string, opts ...EncodeOption) (err error) {
  174. formats := map[string]Format{
  175. ".jpg": JPEG,
  176. ".jpeg": JPEG,
  177. ".png": PNG,
  178. ".tif": TIFF,
  179. ".tiff": TIFF,
  180. ".bmp": BMP,
  181. ".gif": GIF,
  182. }
  183. ext := strings.ToLower(filepath.Ext(filename))
  184. f, ok := formats[ext]
  185. if !ok {
  186. return ErrUnsupportedFormat
  187. }
  188. file, err := fs.Create(filename)
  189. if err != nil {
  190. return err
  191. }
  192. defer func() {
  193. cerr := file.Close()
  194. if err == nil {
  195. err = cerr
  196. }
  197. }()
  198. return Encode(file, img, f, opts...)
  199. }
  200. // New creates a new image with the specified width and height, and fills it with the specified color.
  201. func New(width, height int, fillColor color.Color) *image.NRGBA {
  202. if width <= 0 || height <= 0 {
  203. return &image.NRGBA{}
  204. }
  205. dst := image.NewNRGBA(image.Rect(0, 0, width, height))
  206. c := color.NRGBAModel.Convert(fillColor).(color.NRGBA)
  207. if c.R == 0 && c.G == 0 && c.B == 0 && c.A == 0 {
  208. return dst
  209. }
  210. // Fill the first row.
  211. i := 0
  212. for x := 0; x < width; x++ {
  213. dst.Pix[i+0] = c.R
  214. dst.Pix[i+1] = c.G
  215. dst.Pix[i+2] = c.B
  216. dst.Pix[i+3] = c.A
  217. i += 4
  218. }
  219. // Copy the first row to other rows.
  220. size := width * 4
  221. parallel(1, height, func(ys <-chan int) {
  222. for y := range ys {
  223. i = y * dst.Stride
  224. copy(dst.Pix[i:i+size], dst.Pix[0:size])
  225. }
  226. })
  227. return dst
  228. }
  229. // Clone returns a copy of the given image.
  230. func Clone(img image.Image) *image.NRGBA {
  231. src := newScanner(img)
  232. dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
  233. size := src.w * 4
  234. parallel(0, src.h, func(ys <-chan int) {
  235. for y := range ys {
  236. i := y * dst.Stride
  237. src.scan(0, y, src.w, y+1, dst.Pix[i:i+size])
  238. }
  239. })
  240. return dst
  241. }