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) String() 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) String() 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) String() 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 os.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) os.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([]image.Color, numcolors)
133 for i := 0; i < numcolors; i++ {
134 d.palette[i] = image.RGBA64Color{
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) os.Error {
183 spp := len(d.features[tBitsPerSample]) // samples per pixel
185 width := dst.Bounds().Dx()
187 // Apply horizontal predictor if necessary.
188 // In this case, p contains the color difference to the preceding pixel.
189 // See page 64-65 of the spec.
190 if d.firstVal(tPredictor) == prHorizontal && d.firstVal(tBitsPerSample) == 8 {
191 for y := ymin; y < ymax; y++ {
193 for x := 0; x < (width-1)*spp; x++ {
194 d.buf[d.off] += d.buf[d.off-spp]
202 case mGray, mGrayInvert:
203 img := dst.(*image.Gray)
204 bpp := d.firstVal(tBitsPerSample)
205 max := uint32((1 << bpp) - 1)
206 for y := ymin; y < ymax; y++ {
207 for x := img.Rect.Min.X; x < img.Rect.Max.X; x++ {
208 v := uint8(d.readBits(bpp) * 0xff / max)
209 if d.mode == mGrayInvert {
212 img.SetGray(x, y, image.GrayColor{v})
217 img := dst.(*image.Paletted)
218 bpp := d.firstVal(tBitsPerSample)
219 for y := ymin; y < ymax; y++ {
220 for x := img.Rect.Min.X; x < img.Rect.Max.X; x++ {
221 img.SetColorIndex(x, y, uint8(d.readBits(bpp)))
226 img := dst.(*image.RGBA)
227 for y := ymin; y < ymax; y++ {
228 for x := img.Rect.Min.X; x < img.Rect.Max.X; x++ {
229 img.SetRGBA(x, y, image.RGBAColor{d.buf[d.off], d.buf[d.off+1], d.buf[d.off+2], 0xff})
234 img := dst.(*image.NRGBA)
235 for y := ymin; y < ymax; y++ {
236 for x := img.Rect.Min.X; x < img.Rect.Max.X; x++ {
237 img.SetNRGBA(x, y, image.NRGBAColor{d.buf[d.off], d.buf[d.off+1], d.buf[d.off+2], d.buf[d.off+3]})
242 img := dst.(*image.RGBA)
243 for y := ymin; y < ymax; y++ {
244 for x := img.Rect.Min.X; x < img.Rect.Max.X; x++ {
245 img.SetRGBA(x, y, image.RGBAColor{d.buf[d.off], d.buf[d.off+1], d.buf[d.off+2], d.buf[d.off+3]})
254 func newDecoder(r io.Reader) (*decoder, os.Error) {
257 features: make(map[int][]uint),
261 if _, err := d.r.ReadAt(p, 0); err != nil {
264 switch string(p[0:4]) {
266 d.byteOrder = binary.LittleEndian
268 d.byteOrder = binary.BigEndian
270 return nil, FormatError("malformed header")
273 ifdOffset := int64(d.byteOrder.Uint32(p[4:8]))
275 // The first two bytes contain the number of entries (12 bytes each).
276 if _, err := d.r.ReadAt(p[0:2], ifdOffset); err != nil {
279 numItems := int(d.byteOrder.Uint16(p[0:2]))
281 // All IFD entries are read in one chunk.
282 p = make([]byte, ifdLen*numItems)
283 if _, err := d.r.ReadAt(p, ifdOffset+2); err != nil {
287 for i := 0; i < len(p); i += ifdLen {
288 if err := d.parseIFD(p[i : i+ifdLen]); err != nil {
293 d.config.Width = int(d.firstVal(tImageWidth))
294 d.config.Height = int(d.firstVal(tImageLength))
296 if _, ok := d.features[tBitsPerSample]; !ok {
297 return nil, FormatError("BitsPerSample tag missing")
300 // Determine the image mode.
301 switch d.firstVal(tPhotometricInterpretation) {
303 for _, b := range d.features[tBitsPerSample] {
305 return nil, UnsupportedError("non-8-bit RGB image")
308 d.config.ColorModel = image.RGBAColorModel
309 // RGB images normally have 3 samples per pixel.
310 // If there are more, ExtraSamples (p. 31-32 of the spec)
311 // gives their meaning (usually an alpha channel).
312 switch len(d.features[tBitsPerSample]) {
316 switch d.firstVal(tExtraSamples) {
321 d.config.ColorModel = image.NRGBAColorModel
323 // The extra sample is discarded.
327 return nil, FormatError("wrong number of samples for RGB")
331 d.config.ColorModel = image.PalettedColorModel(d.palette)
334 d.config.ColorModel = image.GrayColorModel
337 d.config.ColorModel = image.GrayColorModel
339 return nil, UnsupportedError("color model")
345 // DecodeConfig returns the color model and dimensions of a TIFF image without
346 // decoding the entire image.
347 func DecodeConfig(r io.Reader) (image.Config, os.Error) {
348 d, err := newDecoder(r)
350 return image.Config{}, err
355 // Decode reads a TIFF image from r and returns it as an image.Image.
356 // The type of Image returned depends on the contents of the TIFF.
357 func Decode(r io.Reader) (img image.Image, err os.Error) {
358 d, err := newDecoder(r)
363 // Check if we have the right number of strips, offsets and counts.
364 rps := int(d.firstVal(tRowsPerStrip))
366 // Assume only one strip.
367 rps = d.config.Height
369 numStrips := (d.config.Height + rps - 1) / rps
370 if rps == 0 || len(d.features[tStripOffsets]) < numStrips || len(d.features[tStripByteCounts]) < numStrips {
371 return nil, FormatError("inconsistent header")
375 case mGray, mGrayInvert:
376 img = image.NewGray(d.config.Width, d.config.Height)
378 img = image.NewPaletted(d.config.Width, d.config.Height, d.palette)
380 img = image.NewNRGBA(d.config.Width, d.config.Height)
382 img = image.NewRGBA(d.config.Width, d.config.Height)
385 for i := 0; i < numStrips; i++ {
387 // The last strip may be shorter.
388 if i == numStrips-1 && d.config.Height%rps != 0 {
389 rps = d.config.Height % rps
391 offset := int64(d.features[tStripOffsets][i])
392 n := int64(d.features[tStripByteCounts][i])
393 switch d.firstVal(tCompression) {
395 // TODO(bsiegert): Avoid copy if r is a tiff.buffer.
396 d.buf = make([]byte, n)
397 _, err = d.r.ReadAt(d.buf, offset)
399 r := lzw.NewReader(io.NewSectionReader(d.r, offset, n), lzw.MSB, 8)
400 d.buf, err = ioutil.ReadAll(r)
402 case cDeflate, cDeflateOld:
403 r, err := zlib.NewReader(io.NewSectionReader(d.r, offset, n))
407 d.buf, err = ioutil.ReadAll(r)
410 err = UnsupportedError("compression")
415 err = d.decode(img, ymin, ymin+rps)
421 image.RegisterFormat("tiff", leHeader, Decode, DecodeConfig)
422 image.RegisterFormat("tiff", beHeader, Decode, DecodeConfig)