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.
5 // Package tiff implements a TIFF image decoder.
7 // The TIFF specification is at http://partners.adobe.com/public/developer/en/tiff/TIFF6.pdf
20 // A FormatError reports that the input is not a valid TIFF image.
21 type FormatError string
23 func (e FormatError) Error() string {
24 return "tiff: invalid format: " + string(e)
27 // An UnsupportedError reports that the input uses a valid but
28 // unimplemented feature.
29 type UnsupportedError string
31 func (e UnsupportedError) Error() string {
32 return "tiff: unsupported feature: " + string(e)
35 // An InternalError reports that an internal error was encountered.
36 type InternalError string
38 func (e InternalError) Error() string {
39 return "tiff: internal error: " + string(e)
44 byteOrder binary.ByteOrder
47 features map[int][]uint
51 off int // Current offset in buf.
52 v uint32 // Buffer value for reading with arbitrary bit depths.
53 nbits uint // Remaining number of bits in v.
56 // firstVal returns the first uint of the features entry with the given tag,
57 // or 0 if the tag does not exist.
58 func (d *decoder) firstVal(tag int) uint {
66 // ifdUint decodes the IFD entry in p, which must be of the Byte, Short
67 // or Long type, and returns the decoded uint values.
68 func (d *decoder) ifdUint(p []byte) (u []uint, err error) {
70 datatype := d.byteOrder.Uint16(p[2:4])
71 count := d.byteOrder.Uint32(p[4:8])
72 if datalen := lengths[datatype] * count; datalen > 4 {
73 // The IFD contains a pointer to the real value.
74 raw = make([]byte, datalen)
75 _, err = d.r.ReadAt(raw, int64(d.byteOrder.Uint32(p[8:12])))
77 raw = p[8 : 8+datalen]
83 u = make([]uint, count)
86 for i := uint32(0); i < count; i++ {
90 for i := uint32(0); i < count; i++ {
91 u[i] = uint(d.byteOrder.Uint16(raw[2*i : 2*(i+1)]))
94 for i := uint32(0); i < count; i++ {
95 u[i] = uint(d.byteOrder.Uint32(raw[4*i : 4*(i+1)]))
98 return nil, UnsupportedError("data type")
103 // parseIFD decides whether the the IFD entry in p is "interesting" and
104 // stows away the data in the decoder.
105 func (d *decoder) parseIFD(p []byte) error {
106 tag := d.byteOrder.Uint16(p[0:2])
110 tPhotometricInterpretation,
118 val, err := d.ifdUint(p)
122 d.features[int(tag)] = val
124 val, err := d.ifdUint(p)
128 numcolors := len(val) / 3
129 if len(val)%3 != 0 || numcolors <= 0 || numcolors > 256 {
130 return FormatError("bad ColorMap length")
132 d.palette = make([]color.Color, numcolors)
133 for i := 0; i < numcolors; i++ {
134 d.palette[i] = color.RGBA64{
136 uint16(val[i+numcolors]),
137 uint16(val[i+2*numcolors]),
142 // Page 27 of the spec: If the SampleFormat is present and
143 // the value is not 1 [= unsigned integer data], a Baseline
144 // TIFF reader that cannot handle the SampleFormat value
145 // must terminate the import process gracefully.
146 val, err := d.ifdUint(p)
150 for _, v := range val {
152 return UnsupportedError("sample format")
159 // readBits reads n bits from the internal buffer starting at the current offset.
160 func (d *decoder) readBits(n uint) uint32 {
163 d.v |= uint32(d.buf[d.off])
169 d.v &^= rv << d.nbits
173 // flushBits discards the unread bits in the buffer used by readBits.
174 // It is used at the end of a line.
175 func (d *decoder) flushBits() {
180 // decode decodes the raw data of an image.
181 // It reads from d.buf and writes the strip with ymin <= y < ymax into dst.
182 func (d *decoder) decode(dst image.Image, ymin, ymax int) error {
185 // Apply horizontal predictor if necessary.
186 // In this case, p contains the color difference to the preceding pixel.
187 // See page 64-65 of the spec.
188 if d.firstVal(tPredictor) == prHorizontal && d.firstVal(tBitsPerSample) == 8 {
190 spp := len(d.features[tBitsPerSample]) // samples per pixel
191 for y := ymin; y < ymax; y++ {
193 for x := 0; x < (dst.Bounds().Dx()-1)*spp; x++ {
194 d.buf[off] += d.buf[off-spp]
201 case mGray, mGrayInvert:
202 img := dst.(*image.Gray)
203 bpp := d.firstVal(tBitsPerSample)
204 max := uint32((1 << bpp) - 1)
205 for y := ymin; y < ymax; y++ {
206 for x := img.Rect.Min.X; x < img.Rect.Max.X; x++ {
207 v := uint8(d.readBits(bpp) * 0xff / max)
208 if d.mode == mGrayInvert {
211 img.SetGray(x, y, color.Gray{v})
216 img := dst.(*image.Paletted)
217 bpp := d.firstVal(tBitsPerSample)
218 for y := ymin; y < ymax; y++ {
219 for x := img.Rect.Min.X; x < img.Rect.Max.X; x++ {
220 img.SetColorIndex(x, y, uint8(d.readBits(bpp)))
225 img := dst.(*image.RGBA)
226 min := (ymin-img.Rect.Min.Y)*img.Stride - img.Rect.Min.X*4
227 max := (ymax-img.Rect.Min.Y)*img.Stride - img.Rect.Min.X*4
229 for i := min; i < max; i += 4 {
230 img.Pix[i+0] = d.buf[off+0]
231 img.Pix[i+1] = d.buf[off+1]
232 img.Pix[i+2] = d.buf[off+2]
237 img := dst.(*image.NRGBA)
238 min := (ymin-img.Rect.Min.Y)*img.Stride - img.Rect.Min.X*4
239 max := (ymax-img.Rect.Min.Y)*img.Stride - img.Rect.Min.X*4
240 if len(d.buf) != max-min {
241 return FormatError("short data strip")
243 copy(img.Pix[min:max], d.buf)
245 img := dst.(*image.RGBA)
246 min := (ymin-img.Rect.Min.Y)*img.Stride - img.Rect.Min.X*4
247 max := (ymax-img.Rect.Min.Y)*img.Stride - img.Rect.Min.X*4
248 if len(d.buf) != max-min {
249 return FormatError("short data strip")
251 copy(img.Pix[min:max], d.buf)
257 func newDecoder(r io.Reader) (*decoder, error) {
260 features: make(map[int][]uint),
264 if _, err := d.r.ReadAt(p, 0); err != nil {
267 switch string(p[0:4]) {
269 d.byteOrder = binary.LittleEndian
271 d.byteOrder = binary.BigEndian
273 return nil, FormatError("malformed header")
276 ifdOffset := int64(d.byteOrder.Uint32(p[4:8]))
278 // The first two bytes contain the number of entries (12 bytes each).
279 if _, err := d.r.ReadAt(p[0:2], ifdOffset); err != nil {
282 numItems := int(d.byteOrder.Uint16(p[0:2]))
284 // All IFD entries are read in one chunk.
285 p = make([]byte, ifdLen*numItems)
286 if _, err := d.r.ReadAt(p, ifdOffset+2); err != nil {
290 for i := 0; i < len(p); i += ifdLen {
291 if err := d.parseIFD(p[i : i+ifdLen]); err != nil {
296 d.config.Width = int(d.firstVal(tImageWidth))
297 d.config.Height = int(d.firstVal(tImageLength))
299 if _, ok := d.features[tBitsPerSample]; !ok {
300 return nil, FormatError("BitsPerSample tag missing")
303 // Determine the image mode.
304 switch d.firstVal(tPhotometricInterpretation) {
306 for _, b := range d.features[tBitsPerSample] {
308 return nil, UnsupportedError("non-8-bit RGB image")
311 d.config.ColorModel = color.RGBAModel
312 // RGB images normally have 3 samples per pixel.
313 // If there are more, ExtraSamples (p. 31-32 of the spec)
314 // gives their meaning (usually an alpha channel).
316 // This implementation does not support extra samples
317 // of an unspecified type.
318 switch len(d.features[tBitsPerSample]) {
322 switch d.firstVal(tExtraSamples) {
327 d.config.ColorModel = color.NRGBAModel
329 return nil, FormatError("wrong number of samples for RGB")
332 return nil, FormatError("wrong number of samples for RGB")
336 d.config.ColorModel = color.Palette(d.palette)
339 d.config.ColorModel = color.GrayModel
342 d.config.ColorModel = color.GrayModel
344 return nil, UnsupportedError("color model")
350 // DecodeConfig returns the color model and dimensions of a TIFF image without
351 // decoding the entire image.
352 func DecodeConfig(r io.Reader) (image.Config, error) {
353 d, err := newDecoder(r)
355 return image.Config{}, err
360 // Decode reads a TIFF image from r and returns it as an image.Image.
361 // The type of Image returned depends on the contents of the TIFF.
362 func Decode(r io.Reader) (img image.Image, err error) {
363 d, err := newDecoder(r)
368 // Check if we have the right number of strips, offsets and counts.
369 rps := int(d.firstVal(tRowsPerStrip))
371 // Assume only one strip.
372 rps = d.config.Height
374 numStrips := (d.config.Height + rps - 1) / rps
375 if rps == 0 || len(d.features[tStripOffsets]) < numStrips || len(d.features[tStripByteCounts]) < numStrips {
376 return nil, FormatError("inconsistent header")
380 case mGray, mGrayInvert:
381 img = image.NewGray(image.Rect(0, 0, d.config.Width, d.config.Height))
383 img = image.NewPaletted(image.Rect(0, 0, d.config.Width, d.config.Height), d.palette)
385 img = image.NewNRGBA(image.Rect(0, 0, d.config.Width, d.config.Height))
387 img = image.NewRGBA(image.Rect(0, 0, d.config.Width, d.config.Height))
390 for i := 0; i < numStrips; i++ {
392 // The last strip may be shorter.
393 if i == numStrips-1 && d.config.Height%rps != 0 {
394 rps = d.config.Height % rps
396 offset := int64(d.features[tStripOffsets][i])
397 n := int64(d.features[tStripByteCounts][i])
398 switch d.firstVal(tCompression) {
400 // TODO(bsiegert): Avoid copy if r is a tiff.buffer.
401 d.buf = make([]byte, n)
402 _, err = d.r.ReadAt(d.buf, offset)
404 r := lzw.NewReader(io.NewSectionReader(d.r, offset, n), lzw.MSB, 8)
405 d.buf, err = ioutil.ReadAll(r)
407 case cDeflate, cDeflateOld:
408 r, err := zlib.NewReader(io.NewSectionReader(d.r, offset, n))
412 d.buf, err = ioutil.ReadAll(r)
415 d.buf, err = unpackBits(io.NewSectionReader(d.r, offset, n))
417 err = UnsupportedError("compression")
422 err = d.decode(img, ymin, ymin+rps)
428 image.RegisterFormat("tiff", leHeader, Decode, DecodeConfig)
429 image.RegisterFormat("tiff", beHeader, Decode, DecodeConfig)