reader.go 20 KB

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