io.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. package imaging
  2. import (
  3. "encoding/binary"
  4. "errors"
  5. "image"
  6. "image/draw"
  7. "image/gif"
  8. "image/jpeg"
  9. "image/png"
  10. "io"
  11. "io/ioutil"
  12. "os"
  13. "path/filepath"
  14. "strings"
  15. "golang.org/x/image/bmp"
  16. "golang.org/x/image/tiff"
  17. )
  18. type fileSystem interface {
  19. Create(string) (io.WriteCloser, error)
  20. Open(string) (io.ReadCloser, error)
  21. }
  22. type localFS struct{}
  23. func (localFS) Create(name string) (io.WriteCloser, error) { return os.Create(name) }
  24. func (localFS) Open(name string) (io.ReadCloser, error) { return os.Open(name) }
  25. var fs fileSystem = localFS{}
  26. type decodeConfig struct {
  27. autoOrientation bool
  28. }
  29. var defaultDecodeConfig = decodeConfig{
  30. autoOrientation: false,
  31. }
  32. // DecodeOption sets an optional parameter for the Decode and Open functions.
  33. type DecodeOption func(*decodeConfig)
  34. // AutoOrientation returns a DecodeOption that sets the auto-orientation mode.
  35. // If auto-orientation is enabled, the image will be transformed after decoding
  36. // according to the EXIF orientation tag (if present). By default it's disabled.
  37. func AutoOrientation(enabled bool) DecodeOption {
  38. return func(c *decodeConfig) {
  39. c.autoOrientation = enabled
  40. }
  41. }
  42. // Decode reads an image from r.
  43. func Decode(r io.Reader, opts ...DecodeOption) (image.Image, error) {
  44. cfg := defaultDecodeConfig
  45. for _, option := range opts {
  46. option(&cfg)
  47. }
  48. if !cfg.autoOrientation {
  49. img, _, err := image.Decode(r)
  50. return img, err
  51. }
  52. var orient orientation
  53. pr, pw := io.Pipe()
  54. r = io.TeeReader(r, pw)
  55. done := make(chan struct{})
  56. go func() {
  57. defer close(done)
  58. orient = readOrientation(pr)
  59. io.Copy(ioutil.Discard, pr)
  60. }()
  61. img, _, err := image.Decode(r)
  62. pw.Close()
  63. <-done
  64. if err != nil {
  65. return nil, err
  66. }
  67. return fixOrientation(img, orient), nil
  68. }
  69. // Open loads an image from file.
  70. //
  71. // Examples:
  72. //
  73. // // Load an image from file.
  74. // img, err := imaging.Open("test.jpg")
  75. //
  76. // // Load an image and transform it depending on the EXIF orientation tag (if present).
  77. // img, err := imaging.Open("test.jpg", imaging.AutoOrientation(true))
  78. //
  79. func Open(filename string, opts ...DecodeOption) (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, opts...)
  86. }
  87. // Format is an image file format.
  88. type Format int
  89. // Image file formats.
  90. const (
  91. JPEG Format = iota
  92. PNG
  93. GIF
  94. TIFF
  95. BMP
  96. )
  97. var formatExts = map[string]Format{
  98. "jpg": JPEG,
  99. "jpeg": JPEG,
  100. "png": PNG,
  101. "gif": GIF,
  102. "tif": TIFF,
  103. "tiff": TIFF,
  104. "bmp": BMP,
  105. }
  106. var formatNames = map[Format]string{
  107. JPEG: "JPEG",
  108. PNG: "PNG",
  109. GIF: "GIF",
  110. TIFF: "TIFF",
  111. BMP: "BMP",
  112. }
  113. func (f Format) String() string {
  114. return formatNames[f]
  115. }
  116. // ErrUnsupportedFormat means the given image format is not supported.
  117. var ErrUnsupportedFormat = errors.New("imaging: unsupported image format")
  118. // FormatFromExtension parses image format from filename extension:
  119. // "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported.
  120. func FormatFromExtension(ext string) (Format, error) {
  121. if f, ok := formatExts[strings.ToLower(strings.TrimPrefix(ext, "."))]; ok {
  122. return f, nil
  123. }
  124. return -1, ErrUnsupportedFormat
  125. }
  126. // FormatFromFilename parses image format from filename:
  127. // "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported.
  128. func FormatFromFilename(filename string) (Format, error) {
  129. ext := filepath.Ext(filename)
  130. return FormatFromExtension(ext)
  131. }
  132. type encodeConfig struct {
  133. jpegQuality int
  134. gifNumColors int
  135. gifQuantizer draw.Quantizer
  136. gifDrawer draw.Drawer
  137. pngCompressionLevel png.CompressionLevel
  138. }
  139. var defaultEncodeConfig = encodeConfig{
  140. jpegQuality: 95,
  141. gifNumColors: 256,
  142. gifQuantizer: nil,
  143. gifDrawer: nil,
  144. pngCompressionLevel: png.DefaultCompression,
  145. }
  146. // EncodeOption sets an optional parameter for the Encode and Save functions.
  147. type EncodeOption func(*encodeConfig)
  148. // JPEGQuality returns an EncodeOption that sets the output JPEG quality.
  149. // Quality ranges from 1 to 100 inclusive, higher is better. Default is 95.
  150. func JPEGQuality(quality int) EncodeOption {
  151. return func(c *encodeConfig) {
  152. c.jpegQuality = quality
  153. }
  154. }
  155. // GIFNumColors returns an EncodeOption that sets the maximum number of colors
  156. // used in the GIF-encoded image. It ranges from 1 to 256. Default is 256.
  157. func GIFNumColors(numColors int) EncodeOption {
  158. return func(c *encodeConfig) {
  159. c.gifNumColors = numColors
  160. }
  161. }
  162. // GIFQuantizer returns an EncodeOption that sets the quantizer that is used to produce
  163. // a palette of the GIF-encoded image.
  164. func GIFQuantizer(quantizer draw.Quantizer) EncodeOption {
  165. return func(c *encodeConfig) {
  166. c.gifQuantizer = quantizer
  167. }
  168. }
  169. // GIFDrawer returns an EncodeOption that sets the drawer that is used to convert
  170. // the source image to the desired palette of the GIF-encoded image.
  171. func GIFDrawer(drawer draw.Drawer) EncodeOption {
  172. return func(c *encodeConfig) {
  173. c.gifDrawer = drawer
  174. }
  175. }
  176. // PNGCompressionLevel returns an EncodeOption that sets the compression level
  177. // of the PNG-encoded image. Default is png.DefaultCompression.
  178. func PNGCompressionLevel(level png.CompressionLevel) EncodeOption {
  179. return func(c *encodeConfig) {
  180. c.pngCompressionLevel = level
  181. }
  182. }
  183. // Encode writes the image img to w in the specified format (JPEG, PNG, GIF, TIFF or BMP).
  184. func Encode(w io.Writer, img image.Image, format Format, opts ...EncodeOption) error {
  185. cfg := defaultEncodeConfig
  186. for _, option := range opts {
  187. option(&cfg)
  188. }
  189. switch format {
  190. case JPEG:
  191. if nrgba, ok := img.(*image.NRGBA); ok && nrgba.Opaque() {
  192. rgba := &image.RGBA{
  193. Pix: nrgba.Pix,
  194. Stride: nrgba.Stride,
  195. Rect: nrgba.Rect,
  196. }
  197. return jpeg.Encode(w, rgba, &jpeg.Options{Quality: cfg.jpegQuality})
  198. }
  199. return jpeg.Encode(w, img, &jpeg.Options{Quality: cfg.jpegQuality})
  200. case PNG:
  201. encoder := png.Encoder{CompressionLevel: cfg.pngCompressionLevel}
  202. return encoder.Encode(w, img)
  203. case GIF:
  204. return gif.Encode(w, img, &gif.Options{
  205. NumColors: cfg.gifNumColors,
  206. Quantizer: cfg.gifQuantizer,
  207. Drawer: cfg.gifDrawer,
  208. })
  209. case TIFF:
  210. return tiff.Encode(w, img, &tiff.Options{Compression: tiff.Deflate, Predictor: true})
  211. case BMP:
  212. return bmp.Encode(w, img)
  213. }
  214. return ErrUnsupportedFormat
  215. }
  216. // Save saves the image to file with the specified filename.
  217. // The format is determined from the filename extension:
  218. // "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported.
  219. //
  220. // Examples:
  221. //
  222. // // Save the image as PNG.
  223. // err := imaging.Save(img, "out.png")
  224. //
  225. // // Save the image as JPEG with optional quality parameter set to 80.
  226. // err := imaging.Save(img, "out.jpg", imaging.JPEGQuality(80))
  227. //
  228. func Save(img image.Image, filename string, opts ...EncodeOption) (err error) {
  229. f, err := FormatFromFilename(filename)
  230. if err != nil {
  231. return err
  232. }
  233. file, err := fs.Create(filename)
  234. if err != nil {
  235. return err
  236. }
  237. err = Encode(file, img, f, opts...)
  238. errc := file.Close()
  239. if err == nil {
  240. err = errc
  241. }
  242. return err
  243. }
  244. // orientation is an EXIF flag that specifies the transformation
  245. // that should be applied to image to display it correctly.
  246. type orientation int
  247. const (
  248. orientationUnspecified = 0
  249. orientationNormal = 1
  250. orientationFlipH = 2
  251. orientationRotate180 = 3
  252. orientationFlipV = 4
  253. orientationTranspose = 5
  254. orientationRotate270 = 6
  255. orientationTransverse = 7
  256. orientationRotate90 = 8
  257. )
  258. // readOrientation tries to read the orientation EXIF flag from image data in r.
  259. // If the EXIF data block is not found or the orientation flag is not found
  260. // or any other error occures while reading the data, it returns the
  261. // orientationUnspecified (0) value.
  262. func readOrientation(r io.Reader) orientation {
  263. const (
  264. markerSOI = 0xffd8
  265. markerAPP1 = 0xffe1
  266. exifHeader = 0x45786966
  267. byteOrderBE = 0x4d4d
  268. byteOrderLE = 0x4949
  269. orientationTag = 0x0112
  270. )
  271. // Check if JPEG SOI marker is present.
  272. var soi uint16
  273. if err := binary.Read(r, binary.BigEndian, &soi); err != nil {
  274. return orientationUnspecified
  275. }
  276. if soi != markerSOI {
  277. return orientationUnspecified // Missing JPEG SOI marker.
  278. }
  279. // Find JPEG APP1 marker.
  280. for {
  281. var marker, size uint16
  282. if err := binary.Read(r, binary.BigEndian, &marker); err != nil {
  283. return orientationUnspecified
  284. }
  285. if err := binary.Read(r, binary.BigEndian, &size); err != nil {
  286. return orientationUnspecified
  287. }
  288. if marker>>8 != 0xff {
  289. return orientationUnspecified // Invalid JPEG marker.
  290. }
  291. if marker == markerAPP1 {
  292. break
  293. }
  294. if size < 2 {
  295. return orientationUnspecified // Invalid block size.
  296. }
  297. if _, err := io.CopyN(ioutil.Discard, r, int64(size-2)); err != nil {
  298. return orientationUnspecified
  299. }
  300. }
  301. // Check if EXIF header is present.
  302. var header uint32
  303. if err := binary.Read(r, binary.BigEndian, &header); err != nil {
  304. return orientationUnspecified
  305. }
  306. if header != exifHeader {
  307. return orientationUnspecified
  308. }
  309. if _, err := io.CopyN(ioutil.Discard, r, 2); err != nil {
  310. return orientationUnspecified
  311. }
  312. // Read byte order information.
  313. var (
  314. byteOrderTag uint16
  315. byteOrder binary.ByteOrder
  316. )
  317. if err := binary.Read(r, binary.BigEndian, &byteOrderTag); err != nil {
  318. return orientationUnspecified
  319. }
  320. switch byteOrderTag {
  321. case byteOrderBE:
  322. byteOrder = binary.BigEndian
  323. case byteOrderLE:
  324. byteOrder = binary.LittleEndian
  325. default:
  326. return orientationUnspecified // Invalid byte order flag.
  327. }
  328. if _, err := io.CopyN(ioutil.Discard, r, 2); err != nil {
  329. return orientationUnspecified
  330. }
  331. // Skip the EXIF offset.
  332. var offset uint32
  333. if err := binary.Read(r, byteOrder, &offset); err != nil {
  334. return orientationUnspecified
  335. }
  336. if offset < 8 {
  337. return orientationUnspecified // Invalid offset value.
  338. }
  339. if _, err := io.CopyN(ioutil.Discard, r, int64(offset-8)); err != nil {
  340. return orientationUnspecified
  341. }
  342. // Read the number of tags.
  343. var numTags uint16
  344. if err := binary.Read(r, byteOrder, &numTags); err != nil {
  345. return orientationUnspecified
  346. }
  347. // Find the orientation tag.
  348. for i := 0; i < int(numTags); i++ {
  349. var tag uint16
  350. if err := binary.Read(r, byteOrder, &tag); err != nil {
  351. return orientationUnspecified
  352. }
  353. if tag != orientationTag {
  354. if _, err := io.CopyN(ioutil.Discard, r, 10); err != nil {
  355. return orientationUnspecified
  356. }
  357. continue
  358. }
  359. if _, err := io.CopyN(ioutil.Discard, r, 6); err != nil {
  360. return orientationUnspecified
  361. }
  362. var val uint16
  363. if err := binary.Read(r, byteOrder, &val); err != nil {
  364. return orientationUnspecified
  365. }
  366. if val < 1 || val > 8 {
  367. return orientationUnspecified // Invalid tag value.
  368. }
  369. return orientation(val)
  370. }
  371. return orientationUnspecified // Missing orientation tag.
  372. }
  373. // fixOrientation applies a transform to img corresponding to the given orientation flag.
  374. func fixOrientation(img image.Image, o orientation) image.Image {
  375. switch o {
  376. case orientationNormal:
  377. case orientationFlipH:
  378. img = FlipH(img)
  379. case orientationFlipV:
  380. img = FlipV(img)
  381. case orientationRotate90:
  382. img = Rotate90(img)
  383. case orientationRotate180:
  384. img = Rotate180(img)
  385. case orientationRotate270:
  386. img = Rotate270(img)
  387. case orientationTranspose:
  388. img = Transpose(img)
  389. case orientationTransverse:
  390. img = Transverse(img)
  391. }
  392. return img
  393. }