helpers.go 4.5 KB

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