You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

reader.go 18 kB

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