helpers.go 6.6 KB

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