helpers.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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. }
  75. var defaultEncodeConfig = encodeConfig{
  76. jpegQuality: 95,
  77. gifNumColors: 256,
  78. gifQuantizer: nil,
  79. gifDrawer: nil,
  80. }
  81. // EncodeOption sets an optional parameter for the Encode and Save functions.
  82. type EncodeOption func(*encodeConfig)
  83. // JPEGQuality returns an EncodeOption that sets the output JPEG quality.
  84. // Quality ranges from 1 to 100 inclusive, higher is better. Default is 95.
  85. func JPEGQuality(quality int) EncodeOption {
  86. return func(c *encodeConfig) {
  87. c.jpegQuality = quality
  88. }
  89. }
  90. // GIFNumColors returns an EncodeOption that sets the maximum number of colors
  91. // used in the GIF-encoded image. It ranges from 1 to 256. Default is 256.
  92. func GIFNumColors(numColors int) EncodeOption {
  93. return func(c *encodeConfig) {
  94. c.gifNumColors = numColors
  95. }
  96. }
  97. // GIFQuantizer returns an EncodeOption that sets the quantizer that is used to produce
  98. // a palette of the GIF-encoded image.
  99. func GIFQuantizer(quantizer draw.Quantizer) EncodeOption {
  100. return func(c *encodeConfig) {
  101. c.gifQuantizer = quantizer
  102. }
  103. }
  104. // GIFDrawer returns an EncodeOption that sets the drawer that is used to convert
  105. // the source image to the desired palette of the GIF-encoded image.
  106. func GIFDrawer(drawer draw.Drawer) EncodeOption {
  107. return func(c *encodeConfig) {
  108. c.gifDrawer = drawer
  109. }
  110. }
  111. // Encode writes the image img to w in the specified format (JPEG, PNG, GIF, TIFF or BMP).
  112. func Encode(w io.Writer, img image.Image, format Format, opts ...EncodeOption) error {
  113. cfg := defaultEncodeConfig
  114. for _, option := range opts {
  115. option(&cfg)
  116. }
  117. var err error
  118. switch format {
  119. case JPEG:
  120. var rgba *image.RGBA
  121. if nrgba, ok := img.(*image.NRGBA); ok {
  122. if nrgba.Opaque() {
  123. rgba = &image.RGBA{
  124. Pix: nrgba.Pix,
  125. Stride: nrgba.Stride,
  126. Rect: nrgba.Rect,
  127. }
  128. }
  129. }
  130. if rgba != nil {
  131. err = jpeg.Encode(w, rgba, &jpeg.Options{Quality: cfg.jpegQuality})
  132. } else {
  133. err = jpeg.Encode(w, img, &jpeg.Options{Quality: cfg.jpegQuality})
  134. }
  135. case PNG:
  136. err = png.Encode(w, img)
  137. case GIF:
  138. err = gif.Encode(w, img, &gif.Options{
  139. NumColors: cfg.gifNumColors,
  140. Quantizer: cfg.gifQuantizer,
  141. Drawer: cfg.gifDrawer,
  142. })
  143. case TIFF:
  144. err = tiff.Encode(w, img, &tiff.Options{Compression: tiff.Deflate, Predictor: true})
  145. case BMP:
  146. err = bmp.Encode(w, img)
  147. default:
  148. err = ErrUnsupportedFormat
  149. }
  150. return err
  151. }
  152. // Save saves the image to file with the specified filename.
  153. // The format is determined from the filename extension: "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported.
  154. //
  155. // Examples:
  156. //
  157. // // Save the image as PNG.
  158. // err := imaging.Save(img, "out.png")
  159. //
  160. // // Save the image as JPEG with optional quality parameter set to 80.
  161. // err := imaging.Save(img, "out.jpg", imaging.JPEGQuality(80))
  162. //
  163. func Save(img image.Image, filename string, opts ...EncodeOption) (err error) {
  164. formats := map[string]Format{
  165. ".jpg": JPEG,
  166. ".jpeg": JPEG,
  167. ".png": PNG,
  168. ".tif": TIFF,
  169. ".tiff": TIFF,
  170. ".bmp": BMP,
  171. ".gif": GIF,
  172. }
  173. ext := strings.ToLower(filepath.Ext(filename))
  174. f, ok := formats[ext]
  175. if !ok {
  176. return ErrUnsupportedFormat
  177. }
  178. file, err := fs.Create(filename)
  179. if err != nil {
  180. return err
  181. }
  182. defer func() {
  183. cerr := file.Close()
  184. if err == nil {
  185. err = cerr
  186. }
  187. }()
  188. return Encode(file, img, f, opts...)
  189. }
  190. // New creates a new image with the specified width and height, and fills it with the specified color.
  191. func New(width, height int, fillColor color.Color) *image.NRGBA {
  192. if width <= 0 || height <= 0 {
  193. return &image.NRGBA{}
  194. }
  195. dst := image.NewNRGBA(image.Rect(0, 0, width, height))
  196. c := color.NRGBAModel.Convert(fillColor).(color.NRGBA)
  197. if c.R == 0 && c.G == 0 && c.B == 0 && c.A == 0 {
  198. return dst
  199. }
  200. // Fill the first row.
  201. i := 0
  202. for x := 0; x < width; x++ {
  203. dst.Pix[i+0] = c.R
  204. dst.Pix[i+1] = c.G
  205. dst.Pix[i+2] = c.B
  206. dst.Pix[i+3] = c.A
  207. i += 4
  208. }
  209. // Copy the first row to other rows.
  210. size := width * 4
  211. parallel(1, height, func(ys <-chan int) {
  212. for y := range ys {
  213. i = y * dst.Stride
  214. copy(dst.Pix[i:i+size], dst.Pix[0:size])
  215. }
  216. })
  217. return dst
  218. }
  219. // Clone returns a copy of the given image.
  220. func Clone(img image.Image) *image.NRGBA {
  221. src := newScanner(img)
  222. dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
  223. size := src.w * 4
  224. parallel(0, src.h, func(ys <-chan int) {
  225. for y := range ys {
  226. i := y * dst.Stride
  227. src.scan(0, y, src.w, y+1, dst.Pix[i:i+size])
  228. }
  229. })
  230. return dst
  231. }