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