helpers.go 4.8 KB

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