git.lucas.co / go_mono
git clone https://git.lucas.co/go_mono.git

tiff/reader.go (20K)

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