writer.go 12 KB

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