writer.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package tiff
  5. import (
  6. "bytes"
  7. "compress/zlib"
  8. "encoding/binary"
  9. "errors"
  10. "image"
  11. "io"
  12. "sort"
  13. )
  14. // The TIFF format allows to choose the order of the different elements freely.
  15. // The basic structure of a TIFF file written by this package is:
  16. //
  17. // 1. Header (8 bytes).
  18. // 2. Image data.
  19. // 3. Image File Directory (IFD).
  20. // 4. "Pointer area" for larger entries in the IFD.
  21. // We only write little-endian TIFF files.
  22. var enc = binary.LittleEndian
  23. // An ifdEntry is a single entry in an Image File Directory.
  24. // A value of type dtRational is composed of two 32-bit values,
  25. // thus data contains two uints (numerator and denominator) for a single number.
  26. type ifdEntry struct {
  27. tag int
  28. datatype int
  29. data []uint32
  30. }
  31. func (e ifdEntry) putData(p []byte) {
  32. for _, d := range e.data {
  33. switch e.datatype {
  34. case dtByte, dtASCII:
  35. p[0] = byte(d)
  36. p = p[1:]
  37. case dtShort:
  38. enc.PutUint16(p, uint16(d))
  39. p = p[2:]
  40. case dtLong, dtRational:
  41. enc.PutUint32(p, uint32(d))
  42. p = p[4:]
  43. }
  44. }
  45. }
  46. type byTag []ifdEntry
  47. func (d byTag) Len() int { return len(d) }
  48. func (d byTag) Less(i, j int) bool { return d[i].tag < d[j].tag }
  49. func (d byTag) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
  50. func encodeGray(w io.Writer, pix []uint8, dx, dy, stride int, predictor bool) error {
  51. if !predictor {
  52. return writePix(w, pix, dy, dx, stride)
  53. }
  54. buf := make([]byte, dx)
  55. for y := 0; y < dy; y++ {
  56. min := y*stride + 0
  57. max := y*stride + dx
  58. off := 0
  59. var v0 uint8
  60. for i := min; i < max; i++ {
  61. v1 := pix[i]
  62. buf[off] = v1 - v0
  63. v0 = v1
  64. off++
  65. }
  66. if _, err := w.Write(buf); err != nil {
  67. return err
  68. }
  69. }
  70. return nil
  71. }
  72. func encodeGray16(w io.Writer, pix []uint8, dx, dy, stride int, predictor bool) error {
  73. buf := make([]byte, dx*2)
  74. for y := 0; y < dy; y++ {
  75. min := y*stride + 0
  76. max := y*stride + dx*2
  77. off := 0
  78. var v0 uint16
  79. for i := min; i < max; i += 2 {
  80. // An image.Gray16's Pix is in big-endian order.
  81. v1 := uint16(pix[i])<<8 | uint16(pix[i+1])
  82. if predictor {
  83. v0, v1 = v1, v1-v0
  84. }
  85. // We only write little-endian TIFF files.
  86. buf[off+0] = byte(v1)
  87. buf[off+1] = byte(v1 >> 8)
  88. off += 2
  89. }
  90. if _, err := w.Write(buf); err != nil {
  91. return err
  92. }
  93. }
  94. return nil
  95. }
  96. func encodeRGBA(w io.Writer, pix []uint8, dx, dy, stride int, predictor bool) error {
  97. if !predictor {
  98. return writePix(w, pix, dy, dx*4, stride)
  99. }
  100. buf := make([]byte, dx*4)
  101. for y := 0; y < dy; y++ {
  102. min := y*stride + 0
  103. max := y*stride + dx*4
  104. off := 0
  105. var r0, g0, b0, a0 uint8
  106. for i := min; i < max; i += 4 {
  107. r1, g1, b1, a1 := pix[i+0], pix[i+1], pix[i+2], pix[i+3]
  108. buf[off+0] = r1 - r0
  109. buf[off+1] = g1 - g0
  110. buf[off+2] = b1 - b0
  111. buf[off+3] = a1 - a0
  112. off += 4
  113. r0, g0, b0, a0 = r1, g1, b1, a1
  114. }
  115. if _, err := w.Write(buf); err != nil {
  116. return err
  117. }
  118. }
  119. return nil
  120. }
  121. func encodeRGBA64(w io.Writer, pix []uint8, dx, dy, stride int, predictor bool) error {
  122. buf := make([]byte, dx*8)
  123. for y := 0; y < dy; y++ {
  124. min := y*stride + 0
  125. max := y*stride + dx*8
  126. off := 0
  127. var r0, g0, b0, a0 uint16
  128. for i := min; i < max; i += 8 {
  129. // An image.RGBA64's Pix is in big-endian order.
  130. r1 := uint16(pix[i+0])<<8 | uint16(pix[i+1])
  131. g1 := uint16(pix[i+2])<<8 | uint16(pix[i+3])
  132. b1 := uint16(pix[i+4])<<8 | uint16(pix[i+5])
  133. a1 := uint16(pix[i+6])<<8 | uint16(pix[i+7])
  134. if predictor {
  135. r0, r1 = r1, r1-r0
  136. g0, g1 = g1, g1-g0
  137. b0, b1 = b1, b1-b0
  138. a0, a1 = a1, a1-a0
  139. }
  140. // We only write little-endian TIFF files.
  141. buf[off+0] = byte(r1)
  142. buf[off+1] = byte(r1 >> 8)
  143. buf[off+2] = byte(g1)
  144. buf[off+3] = byte(g1 >> 8)
  145. buf[off+4] = byte(b1)
  146. buf[off+5] = byte(b1 >> 8)
  147. buf[off+6] = byte(a1)
  148. buf[off+7] = byte(a1 >> 8)
  149. off += 8
  150. }
  151. if _, err := w.Write(buf); err != nil {
  152. return err
  153. }
  154. }
  155. return nil
  156. }
  157. func encode(w io.Writer, m image.Image, predictor bool) error {
  158. bounds := m.Bounds()
  159. buf := make([]byte, 4*bounds.Dx())
  160. for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
  161. off := 0
  162. if predictor {
  163. var r0, g0, b0, a0 uint8
  164. for x := bounds.Min.X; x < bounds.Max.X; x++ {
  165. r, g, b, a := m.At(x, y).RGBA()
  166. r1 := uint8(r >> 8)
  167. g1 := uint8(g >> 8)
  168. b1 := uint8(b >> 8)
  169. a1 := uint8(a >> 8)
  170. buf[off+0] = r1 - r0
  171. buf[off+1] = g1 - g0
  172. buf[off+2] = b1 - b0
  173. buf[off+3] = a1 - a0
  174. off += 4
  175. r0, g0, b0, a0 = r1, g1, b1, a1
  176. }
  177. } else {
  178. for x := bounds.Min.X; x < bounds.Max.X; x++ {
  179. r, g, b, a := m.At(x, y).RGBA()
  180. buf[off+0] = uint8(r >> 8)
  181. buf[off+1] = uint8(g >> 8)
  182. buf[off+2] = uint8(b >> 8)
  183. buf[off+3] = uint8(a >> 8)
  184. off += 4
  185. }
  186. }
  187. if _, err := w.Write(buf); err != nil {
  188. return err
  189. }
  190. }
  191. return nil
  192. }
  193. // writePix writes the internal byte array of an image to w. It is less general
  194. // but much faster then encode. writePix is used when pix directly
  195. // corresponds to one of the TIFF image types.
  196. func writePix(w io.Writer, pix []byte, nrows, length, stride int) error {
  197. if length == stride {
  198. _, err := w.Write(pix[:nrows*length])
  199. return err
  200. }
  201. for ; nrows > 0; nrows-- {
  202. if _, err := w.Write(pix[:length]); err != nil {
  203. return err
  204. }
  205. pix = pix[stride:]
  206. }
  207. return nil
  208. }
  209. func writeIFD(w io.Writer, ifdOffset int, d []ifdEntry) error {
  210. var buf [ifdLen]byte
  211. // Make space for "pointer area" containing IFD entry data
  212. // longer than 4 bytes.
  213. parea := make([]byte, 1024)
  214. pstart := ifdOffset + ifdLen*len(d) + 6
  215. var o int // Current offset in parea.
  216. // The IFD has to be written with the tags in ascending order.
  217. sort.Sort(byTag(d))
  218. // Write the number of entries in this IFD.
  219. if err := binary.Write(w, enc, uint16(len(d))); err != nil {
  220. return err
  221. }
  222. for _, ent := range d {
  223. enc.PutUint16(buf[0:2], uint16(ent.tag))
  224. enc.PutUint16(buf[2:4], uint16(ent.datatype))
  225. count := uint32(len(ent.data))
  226. if ent.datatype == dtRational {
  227. count /= 2
  228. }
  229. enc.PutUint32(buf[4:8], count)
  230. datalen := int(count * lengths[ent.datatype])
  231. if datalen <= 4 {
  232. ent.putData(buf[8:12])
  233. } else {
  234. if (o + datalen) > len(parea) {
  235. newlen := len(parea) + 1024
  236. for (o + datalen) > newlen {
  237. newlen += 1024
  238. }
  239. newarea := make([]byte, newlen)
  240. copy(newarea, parea)
  241. parea = newarea
  242. }
  243. ent.putData(parea[o : o+datalen])
  244. enc.PutUint32(buf[8:12], uint32(pstart+o))
  245. o += datalen
  246. }
  247. if _, err := w.Write(buf[:]); err != nil {
  248. return err
  249. }
  250. }
  251. // The IFD ends with the offset of the next IFD in the file,
  252. // or zero if it is the last one (page 14).
  253. if err := binary.Write(w, enc, uint32(0)); err != nil {
  254. return err
  255. }
  256. _, err := w.Write(parea[:o])
  257. return err
  258. }
  259. // Options are the encoding parameters.
  260. type Options struct {
  261. // Compression is the type of compression used.
  262. Compression CompressionType
  263. // Predictor determines whether a differencing predictor is used;
  264. // if true, instead of each pixel's color, the color difference to the
  265. // preceding one is saved. This improves the compression for certain
  266. // types of images and compressors. For example, it works well for
  267. // photos with Deflate compression.
  268. Predictor bool
  269. }
  270. // Encode writes the image m to w. opt determines the options used for
  271. // encoding, such as the compression type. If opt is nil, an uncompressed
  272. // image is written.
  273. func Encode(w io.Writer, m image.Image, opt *Options) error {
  274. d := m.Bounds().Size()
  275. compression := uint32(cNone)
  276. predictor := false
  277. if opt != nil {
  278. compression = opt.Compression.specValue()
  279. // The predictor field is only used with LZW. See page 64 of the spec.
  280. predictor = opt.Predictor && compression == cLZW
  281. }
  282. _, err := io.WriteString(w, leHeader)
  283. if err != nil {
  284. return err
  285. }
  286. // Compressed data is written into a buffer first, so that we
  287. // know the compressed size.
  288. var buf bytes.Buffer
  289. // dst holds the destination for the pixel data of the image --
  290. // either w or a writer to buf.
  291. var dst io.Writer
  292. // imageLen is the length of the pixel data in bytes.
  293. // The offset of the IFD is imageLen + 8 header bytes.
  294. var imageLen int
  295. switch compression {
  296. case cNone:
  297. dst = w
  298. // Write IFD offset before outputting pixel data.
  299. switch m.(type) {
  300. case *image.Paletted:
  301. imageLen = d.X * d.Y * 1
  302. case *image.Gray:
  303. imageLen = d.X * d.Y * 1
  304. case *image.Gray16:
  305. imageLen = d.X * d.Y * 2
  306. case *image.RGBA64:
  307. imageLen = d.X * d.Y * 8
  308. case *image.NRGBA64:
  309. imageLen = d.X * d.Y * 8
  310. default:
  311. imageLen = d.X * d.Y * 4
  312. }
  313. err = binary.Write(w, enc, uint32(imageLen+8))
  314. if err != nil {
  315. return err
  316. }
  317. case cDeflate:
  318. dst = zlib.NewWriter(&buf)
  319. default:
  320. return errors.New("tiff: unsupported compression")
  321. }
  322. pr := uint32(prNone)
  323. photometricInterpretation := uint32(pRGB)
  324. samplesPerPixel := uint32(4)
  325. bitsPerSample := []uint32{8, 8, 8, 8}
  326. extraSamples := uint32(0)
  327. colorMap := []uint32{}
  328. if predictor {
  329. pr = prHorizontal
  330. }
  331. switch m := m.(type) {
  332. case *image.Paletted:
  333. photometricInterpretation = pPaletted
  334. samplesPerPixel = 1
  335. bitsPerSample = []uint32{8}
  336. colorMap = make([]uint32, 256*3)
  337. for i := 0; i < 256 && i < len(m.Palette); i++ {
  338. r, g, b, _ := m.Palette[i].RGBA()
  339. colorMap[i+0*256] = uint32(r)
  340. colorMap[i+1*256] = uint32(g)
  341. colorMap[i+2*256] = uint32(b)
  342. }
  343. err = encodeGray(dst, m.Pix, d.X, d.Y, m.Stride, predictor)
  344. case *image.Gray:
  345. photometricInterpretation = pBlackIsZero
  346. samplesPerPixel = 1
  347. bitsPerSample = []uint32{8}
  348. err = encodeGray(dst, m.Pix, d.X, d.Y, m.Stride, predictor)
  349. case *image.Gray16:
  350. photometricInterpretation = pBlackIsZero
  351. samplesPerPixel = 1
  352. bitsPerSample = []uint32{16}
  353. err = encodeGray16(dst, m.Pix, d.X, d.Y, m.Stride, predictor)
  354. case *image.NRGBA:
  355. extraSamples = 2 // Unassociated alpha.
  356. err = encodeRGBA(dst, m.Pix, d.X, d.Y, m.Stride, predictor)
  357. case *image.NRGBA64:
  358. extraSamples = 2 // Unassociated alpha.
  359. bitsPerSample = []uint32{16, 16, 16, 16}
  360. err = encodeRGBA64(dst, m.Pix, d.X, d.Y, m.Stride, predictor)
  361. case *image.RGBA:
  362. extraSamples = 1 // Associated alpha.
  363. err = encodeRGBA(dst, m.Pix, d.X, d.Y, m.Stride, predictor)
  364. case *image.RGBA64:
  365. extraSamples = 1 // Associated alpha.
  366. bitsPerSample = []uint32{16, 16, 16, 16}
  367. err = encodeRGBA64(dst, m.Pix, d.X, d.Y, m.Stride, predictor)
  368. default:
  369. extraSamples = 1 // Associated alpha.
  370. err = encode(dst, m, predictor)
  371. }
  372. if err != nil {
  373. return err
  374. }
  375. if compression != cNone {
  376. if err = dst.(io.Closer).Close(); err != nil {
  377. return err
  378. }
  379. imageLen = buf.Len()
  380. if err = binary.Write(w, enc, uint32(imageLen+8)); err != nil {
  381. return err
  382. }
  383. if _, err = buf.WriteTo(w); err != nil {
  384. return err
  385. }
  386. }
  387. ifd := []ifdEntry{
  388. {tImageWidth, dtShort, []uint32{uint32(d.X)}},
  389. {tImageLength, dtShort, []uint32{uint32(d.Y)}},
  390. {tBitsPerSample, dtShort, bitsPerSample},
  391. {tCompression, dtShort, []uint32{compression}},
  392. {tPhotometricInterpretation, dtShort, []uint32{photometricInterpretation}},
  393. {tStripOffsets, dtLong, []uint32{8}},
  394. {tSamplesPerPixel, dtShort, []uint32{samplesPerPixel}},
  395. {tRowsPerStrip, dtShort, []uint32{uint32(d.Y)}},
  396. {tStripByteCounts, dtLong, []uint32{uint32(imageLen)}},
  397. // There is currently no support for storing the image
  398. // resolution, so give a bogus value of 72x72 dpi.
  399. {tXResolution, dtRational, []uint32{72, 1}},
  400. {tYResolution, dtRational, []uint32{72, 1}},
  401. {tResolutionUnit, dtShort, []uint32{resPerInch}},
  402. }
  403. if pr != prNone {
  404. ifd = append(ifd, ifdEntry{tPredictor, dtShort, []uint32{pr}})
  405. }
  406. if len(colorMap) != 0 {
  407. ifd = append(ifd, ifdEntry{tColorMap, dtShort, colorMap})
  408. }
  409. if extraSamples > 0 {
  410. ifd = append(ifd, ifdEntry{tExtraSamples, dtShort, []uint32{extraSamples}})
  411. }
  412. return writeIFD(w, imageLen+8, ifd)
  413. }