io.go 11 KB

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