gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

reader.go (19462B)


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