stdlibwriter.go (14797B)
1 // Code generated by gen.go. DO NOT EDIT. 2 3 // Copyright 2009 The Go Authors. All rights reserved. 4 // Use of this source code is governed by a BSD-style 5 // license that can be found in the LICENSE file. 6 7 package png 8 9 import ( 10 "bufio" 11 "compress/zlib" 12 "encoding/binary" 13 "hash/crc32" 14 "image" 15 "image/color" 16 "io" 17 "strconv" 18 ) 19 20 // Encoder configures encoding PNG images. 21 type Encoder struct { 22 CompressionLevel CompressionLevel 23 24 // BufferPool optionally specifies a buffer pool to get temporary 25 // EncoderBuffers when encoding an image. 26 BufferPool EncoderBufferPool 27 } 28 29 // EncoderBufferPool is an interface for getting and returning temporary 30 // instances of the EncoderBuffer struct. This can be used to reuse buffers 31 // when encoding multiple images. 32 type EncoderBufferPool interface { 33 Get() *EncoderBuffer 34 Put(*EncoderBuffer) 35 } 36 37 // EncoderBuffer holds the buffers used for encoding PNG images. 38 type EncoderBuffer encoder 39 40 type encoder struct { 41 enc *Encoder 42 w io.Writer 43 m image.Image 44 cb int 45 err error 46 header [8]byte 47 footer [4]byte 48 tmp [4 * 256]byte 49 cr [nFilter][]uint8 50 pr []uint8 51 zw *zlib.Writer 52 zwLevel int 53 bw *bufio.Writer 54 } 55 56 // CompressionLevel indicates the compression level. 57 type CompressionLevel int 58 59 const ( 60 DefaultCompression CompressionLevel = 0 61 NoCompression CompressionLevel = -1 62 BestSpeed CompressionLevel = -2 63 BestCompression CompressionLevel = -3 64 65 // Positive CompressionLevel values are reserved to mean a numeric zlib 66 // compression level, although that is not implemented yet. 67 ) 68 69 type opaquer interface { 70 Opaque() bool 71 } 72 73 // Returns whether or not the image is fully opaque. 74 func opaque(m image.Image) bool { 75 if o, ok := m.(opaquer); ok { 76 return o.Opaque() 77 } 78 b := m.Bounds() 79 for y := b.Min.Y; y < b.Max.Y; y++ { 80 for x := b.Min.X; x < b.Max.X; x++ { 81 _, _, _, a := m.At(x, y).RGBA() 82 if a != 0xffff { 83 return false 84 } 85 } 86 } 87 return true 88 } 89 90 // The absolute value of a byte interpreted as a signed int8. 91 func abs8(d uint8) int { 92 if d < 128 { 93 return int(d) 94 } 95 return 256 - int(d) 96 } 97 98 func (e *encoder) writeChunk(b []byte, name string) { 99 if e.err != nil { 100 return 101 } 102 n := uint32(len(b)) 103 if int(n) != len(b) { 104 e.err = UnsupportedError(name + " chunk is too large: " + strconv.Itoa(len(b))) 105 return 106 } 107 binary.BigEndian.PutUint32(e.header[:4], n) 108 e.header[4] = name[0] 109 e.header[5] = name[1] 110 e.header[6] = name[2] 111 e.header[7] = name[3] 112 crc := crc32.NewIEEE() 113 crc.Write(e.header[4:8]) 114 crc.Write(b) 115 binary.BigEndian.PutUint32(e.footer[:4], crc.Sum32()) 116 117 _, e.err = e.w.Write(e.header[:8]) 118 if e.err != nil { 119 return 120 } 121 _, e.err = e.w.Write(b) 122 if e.err != nil { 123 return 124 } 125 _, e.err = e.w.Write(e.footer[:4]) 126 } 127 128 func (e *encoder) writeIHDR() { 129 b := e.m.Bounds() 130 binary.BigEndian.PutUint32(e.tmp[0:4], uint32(b.Dx())) 131 binary.BigEndian.PutUint32(e.tmp[4:8], uint32(b.Dy())) 132 // Set bit depth and color type. 133 switch e.cb { 134 case cbG8: 135 e.tmp[8] = 8 136 e.tmp[9] = ctGrayscale 137 case cbTC8: 138 e.tmp[8] = 8 139 e.tmp[9] = ctTrueColor 140 case cbP8: 141 e.tmp[8] = 8 142 e.tmp[9] = ctPaletted 143 case cbP4: 144 e.tmp[8] = 4 145 e.tmp[9] = ctPaletted 146 case cbP2: 147 e.tmp[8] = 2 148 e.tmp[9] = ctPaletted 149 case cbP1: 150 e.tmp[8] = 1 151 e.tmp[9] = ctPaletted 152 case cbTCA8: 153 e.tmp[8] = 8 154 e.tmp[9] = ctTrueColorAlpha 155 case cbG16: 156 e.tmp[8] = 16 157 e.tmp[9] = ctGrayscale 158 case cbTC16: 159 e.tmp[8] = 16 160 e.tmp[9] = ctTrueColor 161 case cbTCA16: 162 e.tmp[8] = 16 163 e.tmp[9] = ctTrueColorAlpha 164 } 165 e.tmp[10] = 0 // default compression method 166 e.tmp[11] = 0 // default filter method 167 e.tmp[12] = 0 // non-interlaced 168 e.writeChunk(e.tmp[:13], "IHDR") 169 } 170 171 func (e *encoder) writePLTEAndTRNS(p color.Palette) { 172 if len(p) < 1 || len(p) > 256 { 173 e.err = FormatError("bad palette length: " + strconv.Itoa(len(p))) 174 return 175 } 176 last := -1 177 for i, c := range p { 178 c1 := color.NRGBAModel.Convert(c).(color.NRGBA) 179 e.tmp[3*i+0] = c1.R 180 e.tmp[3*i+1] = c1.G 181 e.tmp[3*i+2] = c1.B 182 if c1.A != 0xff { 183 last = i 184 } 185 e.tmp[3*256+i] = c1.A 186 } 187 e.writeChunk(e.tmp[:3*len(p)], "PLTE") 188 if last != -1 { 189 e.writeChunk(e.tmp[3*256:3*256+1+last], "tRNS") 190 } 191 } 192 193 // An encoder is an io.Writer that satisfies writes by writing PNG IDAT chunks, 194 // including an 8-byte header and 4-byte CRC checksum per Write call. Such calls 195 // should be relatively infrequent, since writeIDATs uses a bufio.Writer. 196 // 197 // This method should only be called from writeIDATs (via writeImage). 198 // No other code should treat an encoder as an io.Writer. 199 func (e *encoder) Write(b []byte) (int, error) { 200 e.writeChunk(b, "IDAT") 201 if e.err != nil { 202 return 0, e.err 203 } 204 return len(b), nil 205 } 206 207 // Chooses the filter to use for encoding the current row, and applies it. 208 // The return value is the index of the filter and also of the row in cr that has had it applied. 209 func filter(cr *[nFilter][]byte, pr []byte, bpp int) int { 210 // We try all five filter types, and pick the one that minimizes the sum of absolute differences. 211 // This is the same heuristic that libpng uses, although the filters are attempted in order of 212 // estimated most likely to be minimal (ftUp, ftPaeth, ftNone, ftSub, ftAverage), rather than 213 // in their enumeration order (ftNone, ftSub, ftUp, ftAverage, ftPaeth). 214 cdat0 := cr[0][1:] 215 cdat1 := cr[1][1:] 216 cdat2 := cr[2][1:] 217 cdat3 := cr[3][1:] 218 cdat4 := cr[4][1:] 219 pdat := pr[1:] 220 n := len(cdat0) 221 222 // The up filter. 223 sum := 0 224 for i := 0; i < n; i++ { 225 cdat2[i] = cdat0[i] - pdat[i] 226 sum += abs8(cdat2[i]) 227 } 228 best := sum 229 filter := ftUp 230 231 // The Paeth filter. 232 sum = 0 233 for i := 0; i < bpp; i++ { 234 cdat4[i] = cdat0[i] - pdat[i] 235 sum += abs8(cdat4[i]) 236 } 237 for i := bpp; i < n; i++ { 238 cdat4[i] = cdat0[i] - paeth(cdat0[i-bpp], pdat[i], pdat[i-bpp]) 239 sum += abs8(cdat4[i]) 240 if sum >= best { 241 break 242 } 243 } 244 if sum < best { 245 best = sum 246 filter = ftPaeth 247 } 248 249 // The none filter. 250 sum = 0 251 for i := 0; i < n; i++ { 252 sum += abs8(cdat0[i]) 253 if sum >= best { 254 break 255 } 256 } 257 if sum < best { 258 best = sum 259 filter = ftNone 260 } 261 262 // The sub filter. 263 sum = 0 264 for i := 0; i < bpp; i++ { 265 cdat1[i] = cdat0[i] 266 sum += abs8(cdat1[i]) 267 } 268 for i := bpp; i < n; i++ { 269 cdat1[i] = cdat0[i] - cdat0[i-bpp] 270 sum += abs8(cdat1[i]) 271 if sum >= best { 272 break 273 } 274 } 275 if sum < best { 276 best = sum 277 filter = ftSub 278 } 279 280 // The average filter. 281 sum = 0 282 for i := 0; i < bpp; i++ { 283 cdat3[i] = cdat0[i] - pdat[i]/2 284 sum += abs8(cdat3[i]) 285 } 286 for i := bpp; i < n; i++ { 287 cdat3[i] = cdat0[i] - uint8((int(cdat0[i-bpp])+int(pdat[i]))/2) 288 sum += abs8(cdat3[i]) 289 if sum >= best { 290 break 291 } 292 } 293 if sum < best { 294 filter = ftAverage 295 } 296 297 return filter 298 } 299 300 func zeroMemory(v []uint8) { 301 for i := range v { 302 v[i] = 0 303 } 304 } 305 306 func (e *encoder) writeImage(w io.Writer, m image.Image, cb int, level int) error { 307 if e.zw == nil || e.zwLevel != level { 308 zw, err := zlib.NewWriterLevel(w, level) 309 if err != nil { 310 return err 311 } 312 e.zw = zw 313 e.zwLevel = level 314 } else { 315 e.zw.Reset(w) 316 } 317 defer e.zw.Close() 318 319 bitsPerPixel := 0 320 321 switch cb { 322 case cbG8: 323 bitsPerPixel = 8 324 case cbTC8: 325 bitsPerPixel = 24 326 case cbP8: 327 bitsPerPixel = 8 328 case cbP4: 329 bitsPerPixel = 4 330 case cbP2: 331 bitsPerPixel = 2 332 case cbP1: 333 bitsPerPixel = 1 334 case cbTCA8: 335 bitsPerPixel = 32 336 case cbTC16: 337 bitsPerPixel = 48 338 case cbTCA16: 339 bitsPerPixel = 64 340 case cbG16: 341 bitsPerPixel = 16 342 } 343 344 // cr[*] and pr are the bytes for the current and previous row. 345 // cr[0] is unfiltered (or equivalently, filtered with the ftNone filter). 346 // cr[ft], for non-zero filter types ft, are buffers for transforming cr[0] under the 347 // other PNG filter types. These buffers are allocated once and re-used for each row. 348 // The +1 is for the per-row filter type, which is at cr[*][0]. 349 b := m.Bounds() 350 sz := 1 + (bitsPerPixel*b.Dx()+7)/8 351 for i := range e.cr { 352 if cap(e.cr[i]) < sz { 353 e.cr[i] = make([]uint8, sz) 354 } else { 355 e.cr[i] = e.cr[i][:sz] 356 } 357 e.cr[i][0] = uint8(i) 358 } 359 cr := e.cr 360 if cap(e.pr) < sz { 361 e.pr = make([]uint8, sz) 362 } else { 363 e.pr = e.pr[:sz] 364 zeroMemory(e.pr) 365 } 366 pr := e.pr 367 368 gray, _ := m.(*image.Gray) 369 rgba, _ := m.(*image.RGBA) 370 paletted, _ := m.(*image.Paletted) 371 nrgba, _ := m.(*image.NRGBA) 372 373 for y := b.Min.Y; y < b.Max.Y; y++ { 374 // Convert from colors to bytes. 375 i := 1 376 switch cb { 377 case cbG8: 378 if gray != nil { 379 offset := (y - b.Min.Y) * gray.Stride 380 copy(cr[0][1:], gray.Pix[offset:offset+b.Dx()]) 381 } else { 382 for x := b.Min.X; x < b.Max.X; x++ { 383 c := color.GrayModel.Convert(m.At(x, y)).(color.Gray) 384 cr[0][i] = c.Y 385 i++ 386 } 387 } 388 case cbTC8: 389 // We have previously verified that the alpha value is fully opaque. 390 cr0 := cr[0] 391 stride, pix := 0, []byte(nil) 392 if rgba != nil { 393 stride, pix = rgba.Stride, rgba.Pix 394 } else if nrgba != nil { 395 stride, pix = nrgba.Stride, nrgba.Pix 396 } 397 if stride != 0 { 398 j0 := (y - b.Min.Y) * stride 399 j1 := j0 + b.Dx()*4 400 for j := j0; j < j1; j += 4 { 401 cr0[i+0] = pix[j+0] 402 cr0[i+1] = pix[j+1] 403 cr0[i+2] = pix[j+2] 404 i += 3 405 } 406 } else { 407 for x := b.Min.X; x < b.Max.X; x++ { 408 r, g, b, _ := m.At(x, y).RGBA() 409 cr0[i+0] = uint8(r >> 8) 410 cr0[i+1] = uint8(g >> 8) 411 cr0[i+2] = uint8(b >> 8) 412 i += 3 413 } 414 } 415 case cbP8: 416 if paletted != nil { 417 offset := (y - b.Min.Y) * paletted.Stride 418 copy(cr[0][1:], paletted.Pix[offset:offset+b.Dx()]) 419 } else { 420 pi := m.(image.PalettedImage) 421 for x := b.Min.X; x < b.Max.X; x++ { 422 cr[0][i] = pi.ColorIndexAt(x, y) 423 i += 1 424 } 425 } 426 427 case cbP4, cbP2, cbP1: 428 pi := m.(image.PalettedImage) 429 430 var a uint8 431 var c int 432 pixelsPerByte := 8 / bitsPerPixel 433 for x := b.Min.X; x < b.Max.X; x++ { 434 a = a<<uint(bitsPerPixel) | pi.ColorIndexAt(x, y) 435 c++ 436 if c == pixelsPerByte { 437 cr[0][i] = a 438 i += 1 439 a = 0 440 c = 0 441 } 442 } 443 if c != 0 { 444 for c != pixelsPerByte { 445 a = a << uint(bitsPerPixel) 446 c++ 447 } 448 cr[0][i] = a 449 } 450 451 case cbTCA8: 452 if nrgba != nil { 453 offset := (y - b.Min.Y) * nrgba.Stride 454 copy(cr[0][1:], nrgba.Pix[offset:offset+b.Dx()*4]) 455 } else { 456 // Convert from image.Image (which is alpha-premultiplied) to PNG's non-alpha-premultiplied. 457 for x := b.Min.X; x < b.Max.X; x++ { 458 c := color.NRGBAModel.Convert(m.At(x, y)).(color.NRGBA) 459 cr[0][i+0] = c.R 460 cr[0][i+1] = c.G 461 cr[0][i+2] = c.B 462 cr[0][i+3] = c.A 463 i += 4 464 } 465 } 466 case cbG16: 467 for x := b.Min.X; x < b.Max.X; x++ { 468 c := color.Gray16Model.Convert(m.At(x, y)).(color.Gray16) 469 cr[0][i+0] = uint8(c.Y >> 8) 470 cr[0][i+1] = uint8(c.Y) 471 i += 2 472 } 473 case cbTC16: 474 // We have previously verified that the alpha value is fully opaque. 475 for x := b.Min.X; x < b.Max.X; x++ { 476 r, g, b, _ := m.At(x, y).RGBA() 477 cr[0][i+0] = uint8(r >> 8) 478 cr[0][i+1] = uint8(r) 479 cr[0][i+2] = uint8(g >> 8) 480 cr[0][i+3] = uint8(g) 481 cr[0][i+4] = uint8(b >> 8) 482 cr[0][i+5] = uint8(b) 483 i += 6 484 } 485 case cbTCA16: 486 // Convert from image.Image (which is alpha-premultiplied) to PNG's non-alpha-premultiplied. 487 for x := b.Min.X; x < b.Max.X; x++ { 488 c := color.NRGBA64Model.Convert(m.At(x, y)).(color.NRGBA64) 489 cr[0][i+0] = uint8(c.R >> 8) 490 cr[0][i+1] = uint8(c.R) 491 cr[0][i+2] = uint8(c.G >> 8) 492 cr[0][i+3] = uint8(c.G) 493 cr[0][i+4] = uint8(c.B >> 8) 494 cr[0][i+5] = uint8(c.B) 495 cr[0][i+6] = uint8(c.A >> 8) 496 cr[0][i+7] = uint8(c.A) 497 i += 8 498 } 499 } 500 501 // Apply the filter. 502 // Skip filter for NoCompression and paletted images (cbP8) as 503 // "filters are rarely useful on palette images" and will result 504 // in larger files (see http://www.libpng.org/pub/png/book/chapter09.html). 505 f := ftNone 506 if level != zlib.NoCompression && cb != cbP8 && cb != cbP4 && cb != cbP2 && cb != cbP1 { 507 // Since we skip paletted images we don't have to worry about 508 // bitsPerPixel not being a multiple of 8 509 bpp := bitsPerPixel / 8 510 f = filter(&cr, pr, bpp) 511 } 512 513 // Write the compressed bytes. 514 if _, err := e.zw.Write(cr[f]); err != nil { 515 return err 516 } 517 518 // The current row for y is the previous row for y+1. 519 pr, cr[0] = cr[0], pr 520 } 521 return nil 522 } 523 524 // Write the actual image data to one or more IDAT chunks. 525 func (e *encoder) writeIDATs() { 526 if e.err != nil { 527 return 528 } 529 if e.bw == nil { 530 e.bw = bufio.NewWriterSize(e, 1<<15) 531 } else { 532 e.bw.Reset(e) 533 } 534 e.err = e.writeImage(e.bw, e.m, e.cb, levelToZlib(e.enc.CompressionLevel)) 535 if e.err != nil { 536 return 537 } 538 e.err = e.bw.Flush() 539 } 540 541 // This function is required because we want the zero value of 542 // Encoder.CompressionLevel to map to zlib.DefaultCompression. 543 func levelToZlib(l CompressionLevel) int { 544 switch l { 545 case DefaultCompression: 546 return zlib.DefaultCompression 547 case NoCompression: 548 return zlib.NoCompression 549 case BestSpeed: 550 return zlib.BestSpeed 551 case BestCompression: 552 return zlib.BestCompression 553 default: 554 return zlib.DefaultCompression 555 } 556 } 557 558 func (e *encoder) writeIEND() { e.writeChunk(nil, "IEND") } 559 560 // Encode writes the Image m to w in PNG format. Any Image may be 561 // encoded, but images that are not image.NRGBA might be encoded lossily. 562 func Encode(w io.Writer, m image.Image) error { 563 var e Encoder 564 return e.Encode(w, m) 565 } 566 567 // Encode writes the Image m to w in PNG format. 568 func (enc *Encoder) Encode(w io.Writer, m image.Image) error { 569 // Obviously, negative widths and heights are invalid. Furthermore, the PNG 570 // spec section 11.2.2 says that zero is invalid. Excessively large images are 571 // also rejected. 572 mw, mh := int64(m.Bounds().Dx()), int64(m.Bounds().Dy()) 573 if mw <= 0 || mh <= 0 || mw >= 1<<32 || mh >= 1<<32 { 574 return FormatError("invalid image size: " + strconv.FormatInt(mw, 10) + "x" + strconv.FormatInt(mh, 10)) 575 } 576 577 var e *encoder 578 if enc.BufferPool != nil { 579 buffer := enc.BufferPool.Get() 580 e = (*encoder)(buffer) 581 582 } 583 if e == nil { 584 e = &encoder{} 585 } 586 if enc.BufferPool != nil { 587 defer enc.BufferPool.Put((*EncoderBuffer)(e)) 588 } 589 590 e.enc = enc 591 e.w = w 592 e.m = m 593 594 var pal color.Palette 595 // cbP8 encoding needs PalettedImage's ColorIndexAt method. 596 if _, ok := m.(image.PalettedImage); ok { 597 pal, _ = m.ColorModel().(color.Palette) 598 } 599 if pal != nil { 600 if len(pal) <= 2 { 601 e.cb = cbP1 602 } else if len(pal) <= 4 { 603 e.cb = cbP2 604 } else if len(pal) <= 16 { 605 e.cb = cbP4 606 } else { 607 e.cb = cbP8 608 } 609 } else { 610 switch m.ColorModel() { 611 case color.GrayModel: 612 e.cb = cbG8 613 case color.Gray16Model: 614 e.cb = cbG16 615 case color.RGBAModel, color.NRGBAModel, color.AlphaModel: 616 if opaque(m) { 617 e.cb = cbTC8 618 } else { 619 e.cb = cbTCA8 620 } 621 default: 622 if opaque(m) { 623 e.cb = cbTC16 624 } else { 625 e.cb = cbTCA16 626 } 627 } 628 } 629 630 _, e.err = io.WriteString(w, pngHeader) 631 e.writeIHDR() 632 if pal != nil { 633 e.writePLTEAndTRNS(pal) 634 } 635 e.writeIDATs() 636 e.writeIEND() 637 return e.err 638 }