...

Source file src/golang.org/x/image/tiff/reader.go

Documentation: golang.org/x/image/tiff

     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 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  	if d.firstVal(tPhotometricInterpretation) != pRGB {
   583  		if len(d.features[tBitsPerSample]) != 1 {
   584  			return nil, UnsupportedError("extra samples")
   585  		}
   586  	}
   587  
   588  	return d, nil
   589  }
   590  
   591  // DecodeConfig returns the color model and dimensions of a TIFF image without
   592  // decoding the entire image.
   593  func DecodeConfig(r io.Reader) (image.Config, error) {
   594  	d, err := newDecoder(r)
   595  	if err != nil {
   596  		return image.Config{}, err
   597  	}
   598  	return d.config, nil
   599  }
   600  
   601  func ccittFillOrder(tiffFillOrder uint) ccitt.Order {
   602  	if tiffFillOrder == 2 {
   603  		return ccitt.LSB
   604  	}
   605  	return ccitt.MSB
   606  }
   607  
   608  // Decode reads a TIFF image from r and returns it as an image.Image.
   609  // The type of Image returned depends on the contents of the TIFF.
   610  func Decode(r io.Reader) (img image.Image, err error) {
   611  	d, err := newDecoder(r)
   612  	if err != nil {
   613  		return
   614  	}
   615  
   616  	blockPadding := false
   617  	blockWidth := d.config.Width
   618  	blockHeight := d.config.Height
   619  	blocksAcross := 1
   620  	blocksDown := 1
   621  
   622  	if d.config.Width == 0 {
   623  		blocksAcross = 0
   624  	}
   625  	if d.config.Height == 0 {
   626  		blocksDown = 0
   627  	}
   628  
   629  	var blockOffsets, blockCounts []uint
   630  
   631  	if int(d.firstVal(tTileWidth)) != 0 {
   632  		blockPadding = true
   633  
   634  		blockWidth = int(d.firstVal(tTileWidth))
   635  		blockHeight = int(d.firstVal(tTileLength))
   636  
   637  		// The specification says that tile widths and lengths must be a multiple of 16.
   638  		// We currently permit invalid sizes, but reject anything too small to limit the
   639  		// amount of work a malicious input can force us to perform.
   640  		if blockWidth < 8 || blockHeight < 8 {
   641  			return nil, FormatError("tile size is too small")
   642  		}
   643  
   644  		if blockWidth != 0 {
   645  			blocksAcross = (d.config.Width + blockWidth - 1) / blockWidth
   646  		}
   647  		if blockHeight != 0 {
   648  			blocksDown = (d.config.Height + blockHeight - 1) / blockHeight
   649  		}
   650  
   651  		blockCounts = d.features[tTileByteCounts]
   652  		blockOffsets = d.features[tTileOffsets]
   653  
   654  	} else {
   655  		if int(d.firstVal(tRowsPerStrip)) != 0 {
   656  			blockHeight = int(d.firstVal(tRowsPerStrip))
   657  		}
   658  
   659  		if blockHeight != 0 {
   660  			blocksDown = (d.config.Height + blockHeight - 1) / blockHeight
   661  		}
   662  
   663  		blockOffsets = d.features[tStripOffsets]
   664  		blockCounts = d.features[tStripByteCounts]
   665  	}
   666  
   667  	// Check if we have the right number of strips/tiles, offsets and counts.
   668  	if n := blocksAcross * blocksDown; len(blockOffsets) < n || len(blockCounts) < n {
   669  		return nil, FormatError("inconsistent header")
   670  	}
   671  
   672  	imgRect := image.Rect(0, 0, d.config.Width, d.config.Height)
   673  	switch d.mode {
   674  	case mGray, mGrayInvert:
   675  		if d.bpp == 16 {
   676  			img = image.NewGray16(imgRect)
   677  		} else {
   678  			img = image.NewGray(imgRect)
   679  		}
   680  	case mPaletted:
   681  		img = image.NewPaletted(imgRect, d.palette)
   682  	case mNRGBA:
   683  		if d.bpp == 16 {
   684  			img = image.NewNRGBA64(imgRect)
   685  		} else {
   686  			img = image.NewNRGBA(imgRect)
   687  		}
   688  	case mRGB, mRGBA:
   689  		if d.bpp == 16 {
   690  			img = image.NewRGBA64(imgRect)
   691  		} else {
   692  			img = image.NewRGBA(imgRect)
   693  		}
   694  	}
   695  
   696  	if blocksAcross == 0 || blocksDown == 0 {
   697  		return
   698  	}
   699  	// Maximum data per pixel is 8 bytes (RGBA64).
   700  	blockMaxDataSize := int64(blockWidth) * int64(blockHeight) * 8
   701  	for i := 0; i < blocksAcross; i++ {
   702  		blkW := blockWidth
   703  		if !blockPadding && i == blocksAcross-1 && d.config.Width%blockWidth != 0 {
   704  			blkW = d.config.Width % blockWidth
   705  		}
   706  		for j := 0; j < blocksDown; j++ {
   707  			blkH := blockHeight
   708  			if !blockPadding && j == blocksDown-1 && d.config.Height%blockHeight != 0 {
   709  				blkH = d.config.Height % blockHeight
   710  			}
   711  			offset := int64(blockOffsets[j*blocksAcross+i])
   712  			n := int64(blockCounts[j*blocksAcross+i])
   713  			switch d.firstVal(tCompression) {
   714  
   715  			// According to the spec, Compression does not have a default value,
   716  			// but some tools interpret a missing Compression value as none so we do
   717  			// the same.
   718  			case cNone, 0:
   719  				if b, ok := d.r.(*buffer); ok {
   720  					d.buf, err = b.Slice(int(offset), int(n))
   721  				} else {
   722  					d.buf, err = safeReadAt(d.r, uint64(n), offset)
   723  				}
   724  			case cG3:
   725  				inv := d.firstVal(tPhotometricInterpretation) == pWhiteIsZero
   726  				order := ccittFillOrder(d.firstVal(tFillOrder))
   727  				r := ccitt.NewReader(io.NewSectionReader(d.r, offset, n), order, ccitt.Group3, blkW, blkH, &ccitt.Options{Invert: inv, Align: false})
   728  				d.buf, err = readBuf(r, d.buf, blockMaxDataSize)
   729  			case cG4:
   730  				inv := d.firstVal(tPhotometricInterpretation) == pWhiteIsZero
   731  				order := ccittFillOrder(d.firstVal(tFillOrder))
   732  				r := ccitt.NewReader(io.NewSectionReader(d.r, offset, n), order, ccitt.Group4, blkW, blkH, &ccitt.Options{Invert: inv, Align: false})
   733  				d.buf, err = readBuf(r, d.buf, blockMaxDataSize)
   734  			case cLZW:
   735  				r := lzw.NewReader(io.NewSectionReader(d.r, offset, n), lzw.MSB, 8)
   736  				d.buf, err = readBuf(r, d.buf, blockMaxDataSize)
   737  				r.Close()
   738  			case cDeflate, cDeflateOld:
   739  				var r io.ReadCloser
   740  				r, err = zlib.NewReader(io.NewSectionReader(d.r, offset, n))
   741  				if err != nil {
   742  					return nil, err
   743  				}
   744  				d.buf, err = readBuf(r, d.buf, blockMaxDataSize)
   745  				r.Close()
   746  			case cPackBits:
   747  				d.buf, err = unpackBits(io.NewSectionReader(d.r, offset, n))
   748  			default:
   749  				err = UnsupportedError(fmt.Sprintf("compression value %d", d.firstVal(tCompression)))
   750  			}
   751  			if err != nil {
   752  				return nil, err
   753  			}
   754  
   755  			xmin := i * blockWidth
   756  			ymin := j * blockHeight
   757  			xmax := xmin + blkW
   758  			ymax := ymin + blkH
   759  			err = d.decode(img, xmin, ymin, xmax, ymax)
   760  			if err != nil {
   761  				return nil, err
   762  			}
   763  		}
   764  	}
   765  	return
   766  }
   767  
   768  func readBuf(r io.Reader, buf []byte, lim int64) ([]byte, error) {
   769  	b := bytes.NewBuffer(buf[:0])
   770  	_, err := b.ReadFrom(io.LimitReader(r, lim))
   771  	return b.Bytes(), err
   772  }
   773  
   774  func init() {
   775  	image.RegisterFormat("tiff", leHeader, Decode, DecodeConfig)
   776  	image.RegisterFormat("tiff", beHeader, Decode, DecodeConfig)
   777  }
   778  

View as plain text