reader.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. // Copyright 2011 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 implements a TIFF image decoder and encoder.
  5. //
  6. // The TIFF specification is at http://partners.adobe.com/public/developer/en/tiff/TIFF6.pdf
  7. package tiff // import "golang.org/x/image/tiff"
  8. import (
  9. "bytes"
  10. "compress/zlib"
  11. "encoding/binary"
  12. "fmt"
  13. "image"
  14. "image/color"
  15. "io"
  16. "math"
  17. "golang.org/x/image/ccitt"
  18. "golang.org/x/image/tiff/lzw"
  19. )
  20. // A FormatError reports that the input is not a valid TIFF image.
  21. type FormatError string
  22. func (e FormatError) Error() string {
  23. return "tiff: invalid format: " + string(e)
  24. }
  25. // An UnsupportedError reports that the input uses a valid but
  26. // unimplemented feature.
  27. type UnsupportedError string
  28. func (e UnsupportedError) Error() string {
  29. return "tiff: unsupported feature: " + string(e)
  30. }
  31. var errNoPixels = FormatError("not enough pixel data")
  32. const maxChunkSize = 10 << 20 // 10M
  33. // safeReadtAt is a verbatim copy of internal/saferio.ReadDataAt from the
  34. // standard library, which is used to read data from a reader using a length
  35. // provided by untrusted data, without allocating the entire slice ahead of time
  36. // if it is large (>maxChunkSize). This allows us to avoid allocating giant
  37. // slices before learning that we can't actually read that much data from the
  38. // reader.
  39. func safeReadAt(r io.ReaderAt, n uint64, off int64) ([]byte, error) {
  40. if int64(n) < 0 || n != uint64(int(n)) {
  41. // n is too large to fit in int, so we can't allocate
  42. // a buffer large enough. Treat this as a read failure.
  43. return nil, io.ErrUnexpectedEOF
  44. }
  45. if n < maxChunkSize {
  46. buf := make([]byte, n)
  47. _, err := r.ReadAt(buf, off)
  48. if err != nil {
  49. // io.SectionReader can return EOF for n == 0,
  50. // but for our purposes that is a success.
  51. if err != io.EOF || n > 0 {
  52. return nil, err
  53. }
  54. }
  55. return buf, nil
  56. }
  57. var buf []byte
  58. buf1 := make([]byte, maxChunkSize)
  59. for n > 0 {
  60. next := n
  61. if next > maxChunkSize {
  62. next = maxChunkSize
  63. }
  64. _, err := r.ReadAt(buf1[:next], off)
  65. if err != nil {
  66. return nil, err
  67. }
  68. buf = append(buf, buf1[:next]...)
  69. n -= next
  70. off += int64(next)
  71. }
  72. return buf, nil
  73. }
  74. type decoder struct {
  75. r io.ReaderAt
  76. byteOrder binary.ByteOrder
  77. config image.Config
  78. mode imageMode
  79. bpp uint
  80. features map[int][]uint
  81. palette []color.Color
  82. buf []byte
  83. off int // Current offset in buf.
  84. v uint32 // Buffer value for reading with arbitrary bit depths.
  85. nbits uint // Remaining number of bits in v.
  86. }
  87. // firstVal returns the first uint of the features entry with the given tag,
  88. // or 0 if the tag does not exist.
  89. func (d *decoder) firstVal(tag int) uint {
  90. f := d.features[tag]
  91. if len(f) == 0 {
  92. return 0
  93. }
  94. return f[0]
  95. }
  96. // ifdUint decodes the IFD entry in p, which must be of the Byte, Short
  97. // or Long type, and returns the decoded uint values.
  98. func (d *decoder) ifdUint(p []byte) (u []uint, err error) {
  99. var raw []byte
  100. if len(p) < ifdLen {
  101. return nil, FormatError("bad IFD entry")
  102. }
  103. datatype := d.byteOrder.Uint16(p[2:4])
  104. if dt := int(datatype); dt <= 0 || dt >= len(lengths) {
  105. return nil, UnsupportedError("IFD entry datatype")
  106. }
  107. count := d.byteOrder.Uint32(p[4:8])
  108. if count > math.MaxInt32/lengths[datatype] {
  109. return nil, FormatError("IFD data too large")
  110. }
  111. if datalen := lengths[datatype] * count; datalen > 4 {
  112. // The IFD contains a pointer to the real value.
  113. raw, err = safeReadAt(d.r, uint64(datalen), int64(d.byteOrder.Uint32(p[8:12])))
  114. } else {
  115. raw = p[8 : 8+datalen]
  116. }
  117. if err != nil {
  118. return nil, err
  119. }
  120. u = make([]uint, count)
  121. switch datatype {
  122. case dtByte:
  123. for i := uint32(0); i < count; i++ {
  124. u[i] = uint(raw[i])
  125. }
  126. case dtShort:
  127. for i := uint32(0); i < count; i++ {
  128. u[i] = uint(d.byteOrder.Uint16(raw[2*i : 2*(i+1)]))
  129. }
  130. case dtLong:
  131. for i := uint32(0); i < count; i++ {
  132. u[i] = uint(d.byteOrder.Uint32(raw[4*i : 4*(i+1)]))
  133. }
  134. default:
  135. return nil, UnsupportedError("data type")
  136. }
  137. return u, nil
  138. }
  139. // parseIFD decides whether the IFD entry in p is "interesting" and
  140. // stows away the data in the decoder. It returns the tag number of the
  141. // entry and an error, if any.
  142. func (d *decoder) parseIFD(p []byte) (int, error) {
  143. tag := d.byteOrder.Uint16(p[0:2])
  144. switch tag {
  145. case tBitsPerSample,
  146. tExtraSamples,
  147. tPhotometricInterpretation,
  148. tCompression,
  149. tPredictor,
  150. tStripOffsets,
  151. tStripByteCounts,
  152. tRowsPerStrip,
  153. tTileWidth,
  154. tTileLength,
  155. tTileOffsets,
  156. tTileByteCounts,
  157. tImageLength,
  158. tImageWidth,
  159. tFillOrder,
  160. tT4Options,
  161. tT6Options:
  162. val, err := d.ifdUint(p)
  163. if err != nil {
  164. return 0, err
  165. }
  166. d.features[int(tag)] = val
  167. case tColorMap:
  168. val, err := d.ifdUint(p)
  169. if err != nil {
  170. return 0, err
  171. }
  172. numcolors := len(val) / 3
  173. if len(val)%3 != 0 || numcolors <= 0 || numcolors > 256 {
  174. return 0, FormatError("bad ColorMap length")
  175. }
  176. d.palette = make([]color.Color, numcolors)
  177. for i := 0; i < numcolors; i++ {
  178. d.palette[i] = color.RGBA64{
  179. uint16(val[i]),
  180. uint16(val[i+numcolors]),
  181. uint16(val[i+2*numcolors]),
  182. 0xffff,
  183. }
  184. }
  185. case tSampleFormat:
  186. // Page 27 of the spec: If the SampleFormat is present and
  187. // the value is not 1 [= unsigned integer data], a Baseline
  188. // TIFF reader that cannot handle the SampleFormat value
  189. // must terminate the import process gracefully.
  190. val, err := d.ifdUint(p)
  191. if err != nil {
  192. return 0, err
  193. }
  194. for _, v := range val {
  195. if v != 1 {
  196. return 0, UnsupportedError("sample format")
  197. }
  198. }
  199. }
  200. return int(tag), nil
  201. }
  202. // readBits reads n bits from the internal buffer starting at the current offset.
  203. func (d *decoder) readBits(n uint) (v uint32, ok bool) {
  204. for d.nbits < n {
  205. d.v <<= 8
  206. if d.off >= len(d.buf) {
  207. return 0, false
  208. }
  209. d.v |= uint32(d.buf[d.off])
  210. d.off++
  211. d.nbits += 8
  212. }
  213. d.nbits -= n
  214. rv := d.v >> d.nbits
  215. d.v &^= rv << d.nbits
  216. return rv, true
  217. }
  218. // flushBits discards the unread bits in the buffer used by readBits.
  219. // It is used at the end of a line.
  220. func (d *decoder) flushBits() {
  221. d.v = 0
  222. d.nbits = 0
  223. }
  224. // minInt returns the smaller of x or y.
  225. func minInt(a, b int) int {
  226. if a <= b {
  227. return a
  228. }
  229. return b
  230. }
  231. // decode decodes the raw data of an image.
  232. // It reads from d.buf and writes the strip or tile into dst.
  233. func (d *decoder) decode(dst image.Image, xmin, ymin, xmax, ymax int) error {
  234. d.off = 0
  235. // Apply horizontal predictor if necessary.
  236. // In this case, p contains the color difference to the preceding pixel.
  237. // See page 64-65 of the spec.
  238. if d.firstVal(tPredictor) == prHorizontal {
  239. switch d.bpp {
  240. case 16:
  241. var off int
  242. n := 2 * len(d.features[tBitsPerSample]) // bytes per sample times samples per pixel
  243. for y := ymin; y < ymax; y++ {
  244. off += n
  245. for x := 0; x < (xmax-xmin-1)*n; x += 2 {
  246. if off+2 > len(d.buf) {
  247. return errNoPixels
  248. }
  249. v0 := d.byteOrder.Uint16(d.buf[off-n : off-n+2])
  250. v1 := d.byteOrder.Uint16(d.buf[off : off+2])
  251. d.byteOrder.PutUint16(d.buf[off:off+2], v1+v0)
  252. off += 2
  253. }
  254. }
  255. case 8:
  256. var off int
  257. n := 1 * len(d.features[tBitsPerSample]) // bytes per sample times samples per pixel
  258. for y := ymin; y < ymax; y++ {
  259. off += n
  260. for x := 0; x < (xmax-xmin-1)*n; x++ {
  261. if off >= len(d.buf) {
  262. return errNoPixels
  263. }
  264. d.buf[off] += d.buf[off-n]
  265. off++
  266. }
  267. }
  268. case 1:
  269. return UnsupportedError("horizontal predictor with 1 BitsPerSample")
  270. }
  271. }
  272. rMaxX := minInt(xmax, dst.Bounds().Max.X)
  273. rMaxY := minInt(ymax, dst.Bounds().Max.Y)
  274. switch d.mode {
  275. case mGray, mGrayInvert:
  276. if d.bpp == 16 {
  277. img := dst.(*image.Gray16)
  278. for y := ymin; y < rMaxY; y++ {
  279. for x := xmin; x < rMaxX; x++ {
  280. if d.off+2 > len(d.buf) {
  281. return errNoPixels
  282. }
  283. v := d.byteOrder.Uint16(d.buf[d.off : d.off+2])
  284. d.off += 2
  285. if d.mode == mGrayInvert {
  286. v = 0xffff - v
  287. }
  288. img.SetGray16(x, y, color.Gray16{v})
  289. }
  290. if rMaxX == img.Bounds().Max.X {
  291. d.off += 2 * (xmax - img.Bounds().Max.X)
  292. }
  293. }
  294. } else {
  295. img := dst.(*image.Gray)
  296. max := uint32((1 << d.bpp) - 1)
  297. for y := ymin; y < rMaxY; y++ {
  298. for x := xmin; x < rMaxX; x++ {
  299. v, ok := d.readBits(d.bpp)
  300. if !ok {
  301. return errNoPixels
  302. }
  303. v = v * 0xff / max
  304. if d.mode == mGrayInvert {
  305. v = 0xff - v
  306. }
  307. img.SetGray(x, y, color.Gray{uint8(v)})
  308. }
  309. d.flushBits()
  310. }
  311. }
  312. case mPaletted:
  313. img := dst.(*image.Paletted)
  314. for y := ymin; y < rMaxY; y++ {
  315. for x := xmin; x < rMaxX; x++ {
  316. v, ok := d.readBits(d.bpp)
  317. if !ok {
  318. return errNoPixels
  319. }
  320. img.SetColorIndex(x, y, uint8(v))
  321. }
  322. d.flushBits()
  323. }
  324. case mRGB:
  325. if d.bpp == 16 {
  326. img := dst.(*image.RGBA64)
  327. for y := ymin; y < rMaxY; y++ {
  328. for x := xmin; x < rMaxX; x++ {
  329. if d.off+6 > len(d.buf) {
  330. return errNoPixels
  331. }
  332. r := d.byteOrder.Uint16(d.buf[d.off+0 : d.off+2])
  333. g := d.byteOrder.Uint16(d.buf[d.off+2 : d.off+4])
  334. b := d.byteOrder.Uint16(d.buf[d.off+4 : d.off+6])
  335. d.off += 6
  336. img.SetRGBA64(x, y, color.RGBA64{r, g, b, 0xffff})
  337. }
  338. }
  339. } else {
  340. img := dst.(*image.RGBA)
  341. for y := ymin; y < rMaxY; y++ {
  342. min := img.PixOffset(xmin, y)
  343. max := img.PixOffset(rMaxX, y)
  344. off := (y - ymin) * (xmax - xmin) * 3
  345. for i := min; i < max; i += 4 {
  346. if off+3 > len(d.buf) {
  347. return errNoPixels
  348. }
  349. img.Pix[i+0] = d.buf[off+0]
  350. img.Pix[i+1] = d.buf[off+1]
  351. img.Pix[i+2] = d.buf[off+2]
  352. img.Pix[i+3] = 0xff
  353. off += 3
  354. }
  355. }
  356. }
  357. case mNRGBA:
  358. if d.bpp == 16 {
  359. img := dst.(*image.NRGBA64)
  360. for y := ymin; y < rMaxY; y++ {
  361. for x := xmin; x < rMaxX; x++ {
  362. if d.off+8 > len(d.buf) {
  363. return errNoPixels
  364. }
  365. r := d.byteOrder.Uint16(d.buf[d.off+0 : d.off+2])
  366. g := d.byteOrder.Uint16(d.buf[d.off+2 : d.off+4])
  367. b := d.byteOrder.Uint16(d.buf[d.off+4 : d.off+6])
  368. a := d.byteOrder.Uint16(d.buf[d.off+6 : d.off+8])
  369. d.off += 8
  370. img.SetNRGBA64(x, y, color.NRGBA64{r, g, b, a})
  371. }
  372. }
  373. } else {
  374. img := dst.(*image.NRGBA)
  375. for y := ymin; y < rMaxY; y++ {
  376. min := img.PixOffset(xmin, y)
  377. max := img.PixOffset(rMaxX, y)
  378. i0, i1 := (y-ymin)*(xmax-xmin)*4, (y-ymin+1)*(xmax-xmin)*4
  379. if i1 > len(d.buf) {
  380. return errNoPixels
  381. }
  382. copy(img.Pix[min:max], d.buf[i0:i1])
  383. }
  384. }
  385. case mRGBA:
  386. if d.bpp == 16 {
  387. img := dst.(*image.RGBA64)
  388. for y := ymin; y < rMaxY; y++ {
  389. for x := xmin; x < rMaxX; x++ {
  390. if d.off+8 > len(d.buf) {
  391. return errNoPixels
  392. }
  393. r := d.byteOrder.Uint16(d.buf[d.off+0 : d.off+2])
  394. g := d.byteOrder.Uint16(d.buf[d.off+2 : d.off+4])
  395. b := d.byteOrder.Uint16(d.buf[d.off+4 : d.off+6])
  396. a := d.byteOrder.Uint16(d.buf[d.off+6 : d.off+8])
  397. d.off += 8
  398. img.SetRGBA64(x, y, color.RGBA64{r, g, b, a})
  399. }
  400. }
  401. } else {
  402. img := dst.(*image.RGBA)
  403. for y := ymin; y < rMaxY; y++ {
  404. min := img.PixOffset(xmin, y)
  405. max := img.PixOffset(rMaxX, y)
  406. i0, i1 := (y-ymin)*(xmax-xmin)*4, (y-ymin+1)*(xmax-xmin)*4
  407. if i1 > len(d.buf) {
  408. return errNoPixels
  409. }
  410. copy(img.Pix[min:max], d.buf[i0:i1])
  411. }
  412. }
  413. }
  414. return nil
  415. }
  416. func newDecoder(r io.Reader) (*decoder, error) {
  417. d := &decoder{
  418. r: newReaderAt(r),
  419. features: make(map[int][]uint),
  420. }
  421. p := make([]byte, 8)
  422. if _, err := d.r.ReadAt(p, 0); err != nil {
  423. if err == io.EOF {
  424. err = io.ErrUnexpectedEOF
  425. }
  426. return nil, err
  427. }
  428. switch string(p[0:4]) {
  429. case leHeader:
  430. d.byteOrder = binary.LittleEndian
  431. case beHeader:
  432. d.byteOrder = binary.BigEndian
  433. default:
  434. return nil, FormatError("malformed header")
  435. }
  436. ifdOffset := int64(d.byteOrder.Uint32(p[4:8]))
  437. // The first two bytes contain the number of entries (12 bytes each).
  438. if _, err := d.r.ReadAt(p[0:2], ifdOffset); err != nil {
  439. return nil, err
  440. }
  441. numItems := int(d.byteOrder.Uint16(p[0:2]))
  442. // All IFD entries are read in one chunk.
  443. var err error
  444. p, err = safeReadAt(d.r, uint64(ifdLen*numItems), ifdOffset+2)
  445. if err != nil {
  446. return nil, err
  447. }
  448. prevTag := -1
  449. for i := 0; i < len(p); i += ifdLen {
  450. tag, err := d.parseIFD(p[i : i+ifdLen])
  451. if err != nil {
  452. return nil, err
  453. }
  454. if tag <= prevTag {
  455. return nil, FormatError("tags are not sorted in ascending order")
  456. }
  457. prevTag = tag
  458. }
  459. d.config.Width = int(d.firstVal(tImageWidth))
  460. d.config.Height = int(d.firstVal(tImageLength))
  461. if _, ok := d.features[tBitsPerSample]; !ok {
  462. // Default is 1 per specification.
  463. d.features[tBitsPerSample] = []uint{1}
  464. }
  465. d.bpp = d.firstVal(tBitsPerSample)
  466. switch d.bpp {
  467. case 0:
  468. return nil, FormatError("BitsPerSample must not be 0")
  469. case 1, 8, 16:
  470. // Nothing to do, these are accepted by this implementation.
  471. default:
  472. return nil, UnsupportedError(fmt.Sprintf("BitsPerSample of %v", d.bpp))
  473. }
  474. // Determine the image mode.
  475. switch d.firstVal(tPhotometricInterpretation) {
  476. case pRGB:
  477. if d.bpp == 16 {
  478. for _, b := range d.features[tBitsPerSample] {
  479. if b != 16 {
  480. return nil, FormatError("wrong number of samples for 16bit RGB")
  481. }
  482. }
  483. } else {
  484. for _, b := range d.features[tBitsPerSample] {
  485. if b != 8 {
  486. return nil, FormatError("wrong number of samples for 8bit RGB")
  487. }
  488. }
  489. }
  490. // RGB images normally have 3 samples per pixel.
  491. // If there are more, ExtraSamples (p. 31-32 of the spec)
  492. // gives their meaning (usually an alpha channel).
  493. //
  494. // This implementation does not support extra samples
  495. // of an unspecified type.
  496. switch len(d.features[tBitsPerSample]) {
  497. case 3:
  498. d.mode = mRGB
  499. if d.bpp == 16 {
  500. d.config.ColorModel = color.RGBA64Model
  501. } else {
  502. d.config.ColorModel = color.RGBAModel
  503. }
  504. case 4:
  505. switch d.firstVal(tExtraSamples) {
  506. case 1:
  507. d.mode = mRGBA
  508. if d.bpp == 16 {
  509. d.config.ColorModel = color.RGBA64Model
  510. } else {
  511. d.config.ColorModel = color.RGBAModel
  512. }
  513. case 2:
  514. d.mode = mNRGBA
  515. if d.bpp == 16 {
  516. d.config.ColorModel = color.NRGBA64Model
  517. } else {
  518. d.config.ColorModel = color.NRGBAModel
  519. }
  520. default:
  521. return nil, FormatError("wrong number of samples for RGB")
  522. }
  523. default:
  524. return nil, FormatError("wrong number of samples for RGB")
  525. }
  526. case pPaletted:
  527. d.mode = mPaletted
  528. d.config.ColorModel = color.Palette(d.palette)
  529. case pWhiteIsZero:
  530. d.mode = mGrayInvert
  531. if d.bpp == 16 {
  532. d.config.ColorModel = color.Gray16Model
  533. } else {
  534. d.config.ColorModel = color.GrayModel
  535. }
  536. case pBlackIsZero:
  537. d.mode = mGray
  538. if d.bpp == 16 {
  539. d.config.ColorModel = color.Gray16Model
  540. } else {
  541. d.config.ColorModel = color.GrayModel
  542. }
  543. default:
  544. return nil, UnsupportedError("color model")
  545. }
  546. if d.firstVal(tPhotometricInterpretation) != pRGB {
  547. if len(d.features[tBitsPerSample]) != 1 {
  548. return nil, UnsupportedError("extra samples")
  549. }
  550. }
  551. return d, nil
  552. }
  553. // DecodeConfig returns the color model and dimensions of a TIFF image without
  554. // decoding the entire image.
  555. func DecodeConfig(r io.Reader) (image.Config, error) {
  556. d, err := newDecoder(r)
  557. if err != nil {
  558. return image.Config{}, err
  559. }
  560. return d.config, nil
  561. }
  562. func ccittFillOrder(tiffFillOrder uint) ccitt.Order {
  563. if tiffFillOrder == 2 {
  564. return ccitt.LSB
  565. }
  566. return ccitt.MSB
  567. }
  568. // Decode reads a TIFF image from r and returns it as an image.Image.
  569. // The type of Image returned depends on the contents of the TIFF.
  570. func Decode(r io.Reader) (img image.Image, err error) {
  571. d, err := newDecoder(r)
  572. if err != nil {
  573. return
  574. }
  575. blockPadding := false
  576. blockWidth := d.config.Width
  577. blockHeight := d.config.Height
  578. blocksAcross := 1
  579. blocksDown := 1
  580. if d.config.Width == 0 {
  581. blocksAcross = 0
  582. }
  583. if d.config.Height == 0 {
  584. blocksDown = 0
  585. }
  586. var blockOffsets, blockCounts []uint
  587. if int(d.firstVal(tTileWidth)) != 0 {
  588. blockPadding = true
  589. blockWidth = int(d.firstVal(tTileWidth))
  590. blockHeight = int(d.firstVal(tTileLength))
  591. // The specification says that tile widths and lengths must be a multiple of 16.
  592. // We currently permit invalid sizes, but reject anything too small to limit the
  593. // amount of work a malicious input can force us to perform.
  594. if blockWidth < 8 || blockHeight < 8 {
  595. return nil, FormatError("tile size is too small")
  596. }
  597. if blockWidth != 0 {
  598. blocksAcross = (d.config.Width + blockWidth - 1) / blockWidth
  599. }
  600. if blockHeight != 0 {
  601. blocksDown = (d.config.Height + blockHeight - 1) / blockHeight
  602. }
  603. blockCounts = d.features[tTileByteCounts]
  604. blockOffsets = d.features[tTileOffsets]
  605. } else {
  606. if int(d.firstVal(tRowsPerStrip)) != 0 {
  607. blockHeight = int(d.firstVal(tRowsPerStrip))
  608. }
  609. if blockHeight != 0 {
  610. blocksDown = (d.config.Height + blockHeight - 1) / blockHeight
  611. }
  612. blockOffsets = d.features[tStripOffsets]
  613. blockCounts = d.features[tStripByteCounts]
  614. }
  615. // Check if we have the right number of strips/tiles, offsets and counts.
  616. if n := blocksAcross * blocksDown; len(blockOffsets) < n || len(blockCounts) < n {
  617. return nil, FormatError("inconsistent header")
  618. }
  619. imgRect := image.Rect(0, 0, d.config.Width, d.config.Height)
  620. switch d.mode {
  621. case mGray, mGrayInvert:
  622. if d.bpp == 16 {
  623. img = image.NewGray16(imgRect)
  624. } else {
  625. img = image.NewGray(imgRect)
  626. }
  627. case mPaletted:
  628. img = image.NewPaletted(imgRect, d.palette)
  629. case mNRGBA:
  630. if d.bpp == 16 {
  631. img = image.NewNRGBA64(imgRect)
  632. } else {
  633. img = image.NewNRGBA(imgRect)
  634. }
  635. case mRGB, mRGBA:
  636. if d.bpp == 16 {
  637. img = image.NewRGBA64(imgRect)
  638. } else {
  639. img = image.NewRGBA(imgRect)
  640. }
  641. }
  642. if blocksAcross == 0 || blocksDown == 0 {
  643. return
  644. }
  645. // Maximum data per pixel is 8 bytes (RGBA64).
  646. blockMaxDataSize := int64(blockWidth) * int64(blockHeight) * 8
  647. for i := 0; i < blocksAcross; i++ {
  648. blkW := blockWidth
  649. if !blockPadding && i == blocksAcross-1 && d.config.Width%blockWidth != 0 {
  650. blkW = d.config.Width % blockWidth
  651. }
  652. for j := 0; j < blocksDown; j++ {
  653. blkH := blockHeight
  654. if !blockPadding && j == blocksDown-1 && d.config.Height%blockHeight != 0 {
  655. blkH = d.config.Height % blockHeight
  656. }
  657. offset := int64(blockOffsets[j*blocksAcross+i])
  658. n := int64(blockCounts[j*blocksAcross+i])
  659. switch d.firstVal(tCompression) {
  660. // According to the spec, Compression does not have a default value,
  661. // but some tools interpret a missing Compression value as none so we do
  662. // the same.
  663. case cNone, 0:
  664. if b, ok := d.r.(*buffer); ok {
  665. d.buf, err = b.Slice(int(offset), int(n))
  666. } else {
  667. d.buf, err = safeReadAt(d.r, uint64(n), offset)
  668. }
  669. case cG3:
  670. inv := d.firstVal(tPhotometricInterpretation) == pWhiteIsZero
  671. order := ccittFillOrder(d.firstVal(tFillOrder))
  672. r := ccitt.NewReader(io.NewSectionReader(d.r, offset, n), order, ccitt.Group3, blkW, blkH, &ccitt.Options{Invert: inv, Align: false})
  673. d.buf, err = readBuf(r, d.buf, blockMaxDataSize)
  674. case cG4:
  675. inv := d.firstVal(tPhotometricInterpretation) == pWhiteIsZero
  676. order := ccittFillOrder(d.firstVal(tFillOrder))
  677. r := ccitt.NewReader(io.NewSectionReader(d.r, offset, n), order, ccitt.Group4, blkW, blkH, &ccitt.Options{Invert: inv, Align: false})
  678. d.buf, err = readBuf(r, d.buf, blockMaxDataSize)
  679. case cLZW:
  680. r := lzw.NewReader(io.NewSectionReader(d.r, offset, n), lzw.MSB, 8)
  681. d.buf, err = readBuf(r, d.buf, blockMaxDataSize)
  682. r.Close()
  683. case cDeflate, cDeflateOld:
  684. var r io.ReadCloser
  685. r, err = zlib.NewReader(io.NewSectionReader(d.r, offset, n))
  686. if err != nil {
  687. return nil, err
  688. }
  689. d.buf, err = readBuf(r, d.buf, blockMaxDataSize)
  690. r.Close()
  691. case cPackBits:
  692. d.buf, err = unpackBits(io.NewSectionReader(d.r, offset, n))
  693. default:
  694. err = UnsupportedError(fmt.Sprintf("compression value %d", d.firstVal(tCompression)))
  695. }
  696. if err != nil {
  697. return nil, err
  698. }
  699. xmin := i * blockWidth
  700. ymin := j * blockHeight
  701. xmax := xmin + blkW
  702. ymax := ymin + blkH
  703. err = d.decode(img, xmin, ymin, xmax, ymax)
  704. if err != nil {
  705. return nil, err
  706. }
  707. }
  708. }
  709. return
  710. }
  711. func readBuf(r io.Reader, buf []byte, lim int64) ([]byte, error) {
  712. b := bytes.NewBuffer(buf[:0])
  713. _, err := b.ReadFrom(io.LimitReader(r, lim))
  714. return b.Bytes(), err
  715. }
  716. func init() {
  717. image.RegisterFormat("tiff", leHeader, Decode, DecodeConfig)
  718. image.RegisterFormat("tiff", beHeader, Decode, DecodeConfig)
  719. }