1 // Copyright 2009 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.
29 func writeUint32(b []uint8, u uint32) {
36 type opaquer interface {
40 // Returns whether or not the image is fully opaque.
41 func opaque(m image.Image) bool {
42 if o, ok := m.(opaquer); ok {
46 for y := b.Min.Y; y < b.Max.Y; y++ {
47 for x := b.Min.X; x < b.Max.X; x++ {
48 _, _, _, a := m.At(x, y).RGBA()
57 // The absolute value of a byte interpreted as a signed int8.
58 func abs8(d uint8) int {
65 func (e *encoder) writeChunk(b []byte, name string) {
71 e.err = UnsupportedError(name + " chunk is too large: " + strconv.Itoa(len(b)))
74 writeUint32(e.header[0:4], n)
79 crc := crc32.NewIEEE()
80 crc.Write(e.header[4:8])
82 writeUint32(e.footer[0:4], crc.Sum32())
84 _, e.err = e.w.Write(e.header[0:8])
88 _, e.err = e.w.Write(b)
92 _, e.err = e.w.Write(e.footer[0:4])
95 func (e *encoder) writeIHDR() {
97 writeUint32(e.tmp[0:4], uint32(b.Dx()))
98 writeUint32(e.tmp[4:8], uint32(b.Dy()))
99 // Set bit depth and color type.
103 e.tmp[9] = ctGrayscale
106 e.tmp[9] = ctTrueColor
109 e.tmp[9] = ctPaletted
112 e.tmp[9] = ctTrueColorAlpha
115 e.tmp[9] = ctGrayscale
118 e.tmp[9] = ctTrueColor
121 e.tmp[9] = ctTrueColorAlpha
123 e.tmp[10] = 0 // default compression method
124 e.tmp[11] = 0 // default filter method
125 e.tmp[12] = 0 // non-interlaced
126 e.writeChunk(e.tmp[0:13], "IHDR")
129 func (e *encoder) writePLTE(p color.Palette) {
130 if len(p) < 1 || len(p) > 256 {
131 e.err = FormatError("bad palette length: " + strconv.Itoa(len(p)))
134 for i, c := range p {
135 r, g, b, _ := c.RGBA()
136 e.tmp[3*i+0] = uint8(r >> 8)
137 e.tmp[3*i+1] = uint8(g >> 8)
138 e.tmp[3*i+2] = uint8(b >> 8)
140 e.writeChunk(e.tmp[0:3*len(p)], "PLTE")
143 func (e *encoder) maybeWritetRNS(p color.Palette) {
145 for i, c := range p {
146 _, _, _, a := c.RGBA()
150 e.tmp[i] = uint8(a >> 8)
155 e.writeChunk(e.tmp[:last+1], "tRNS")
158 // An encoder is an io.Writer that satisfies writes by writing PNG IDAT chunks,
159 // including an 8-byte header and 4-byte CRC checksum per Write call. Such calls
160 // should be relatively infrequent, since writeIDATs uses a bufio.Writer.
162 // This method should only be called from writeIDATs (via writeImage).
163 // No other code should treat an encoder as an io.Writer.
164 func (e *encoder) Write(b []byte) (int, os.Error) {
165 e.writeChunk(b, "IDAT")
172 // Chooses the filter to use for encoding the current row, and applies it.
173 // The return value is the index of the filter and also of the row in cr that has had it applied.
174 func filter(cr *[nFilter][]byte, pr []byte, bpp int) int {
175 // We try all five filter types, and pick the one that minimizes the sum of absolute differences.
176 // This is the same heuristic that libpng uses, although the filters are attempted in order of
177 // estimated most likely to be minimal (ftUp, ftPaeth, ftNone, ftSub, ftAverage), rather than
178 // in their enumeration order (ftNone, ftSub, ftUp, ftAverage, ftPaeth).
189 for i := 0; i < n; i++ {
190 cdat2[i] = cdat0[i] - pdat[i]
191 sum += abs8(cdat2[i])
198 for i := 0; i < bpp; i++ {
199 cdat4[i] = cdat0[i] - paeth(0, pdat[i], 0)
200 sum += abs8(cdat4[i])
202 for i := bpp; i < n; i++ {
203 cdat4[i] = cdat0[i] - paeth(cdat0[i-bpp], pdat[i], pdat[i-bpp])
204 sum += abs8(cdat4[i])
216 for i := 0; i < n; i++ {
217 sum += abs8(cdat0[i])
229 for i := 0; i < bpp; i++ {
231 sum += abs8(cdat1[i])
233 for i := bpp; i < n; i++ {
234 cdat1[i] = cdat0[i] - cdat0[i-bpp]
235 sum += abs8(cdat1[i])
245 // The average filter.
247 for i := 0; i < bpp; i++ {
248 cdat3[i] = cdat0[i] - pdat[i]/2
249 sum += abs8(cdat3[i])
251 for i := bpp; i < n; i++ {
252 cdat3[i] = cdat0[i] - uint8((int(cdat0[i-bpp])+int(pdat[i]))/2)
253 sum += abs8(cdat3[i])
266 func writeImage(w io.Writer, m image.Image, cb int) os.Error {
267 zw, err := zlib.NewWriter(w)
273 bpp := 0 // Bytes per pixel.
291 // cr[*] and pr are the bytes for the current and previous row.
292 // cr[0] is unfiltered (or equivalently, filtered with the ftNone filter).
293 // cr[ft], for non-zero filter types ft, are buffers for transforming cr[0] under the
294 // other PNG filter types. These buffers are allocated once and re-used for each row.
295 // The +1 is for the per-row filter type, which is at cr[*][0].
297 var cr [nFilter][]uint8
299 cr[i] = make([]uint8, 1+bpp*b.Dx())
302 pr := make([]uint8, 1+bpp*b.Dx())
304 for y := b.Min.Y; y < b.Max.Y; y++ {
305 // Convert from colors to bytes.
309 for x := b.Min.X; x < b.Max.X; x++ {
310 c := color.GrayModel.Convert(m.At(x, y)).(color.Gray)
315 // We have previously verified that the alpha value is fully opaque.
317 if rgba, _ := m.(*image.RGBA); rgba != nil {
318 j0 := (y - b.Min.Y) * rgba.Stride
320 for j := j0; j < j1; j += 4 {
321 cr0[i+0] = rgba.Pix[j+0]
322 cr0[i+1] = rgba.Pix[j+1]
323 cr0[i+2] = rgba.Pix[j+2]
327 for x := b.Min.X; x < b.Max.X; x++ {
328 r, g, b, _ := m.At(x, y).RGBA()
329 cr0[i+0] = uint8(r >> 8)
330 cr0[i+1] = uint8(g >> 8)
331 cr0[i+2] = uint8(b >> 8)
336 if p, _ := m.(*image.Paletted); p != nil {
337 offset := (y - b.Min.Y) * p.Stride
338 copy(cr[0][1:], p.Pix[offset:offset+b.Dx()])
340 pi := m.(image.PalettedImage)
341 for x := b.Min.X; x < b.Max.X; x++ {
342 cr[0][i] = pi.ColorIndexAt(x, y)
347 // Convert from image.Image (which is alpha-premultiplied) to PNG's non-alpha-premultiplied.
348 for x := b.Min.X; x < b.Max.X; x++ {
349 c := color.NRGBAModel.Convert(m.At(x, y)).(color.NRGBA)
357 for x := b.Min.X; x < b.Max.X; x++ {
358 c := color.Gray16Model.Convert(m.At(x, y)).(color.Gray16)
359 cr[0][i+0] = uint8(c.Y >> 8)
360 cr[0][i+1] = uint8(c.Y)
364 // We have previously verified that the alpha value is fully opaque.
365 for x := b.Min.X; x < b.Max.X; x++ {
366 r, g, b, _ := m.At(x, y).RGBA()
367 cr[0][i+0] = uint8(r >> 8)
368 cr[0][i+1] = uint8(r)
369 cr[0][i+2] = uint8(g >> 8)
370 cr[0][i+3] = uint8(g)
371 cr[0][i+4] = uint8(b >> 8)
372 cr[0][i+5] = uint8(b)
376 // Convert from image.Image (which is alpha-premultiplied) to PNG's non-alpha-premultiplied.
377 for x := b.Min.X; x < b.Max.X; x++ {
378 c := color.NRGBA64Model.Convert(m.At(x, y)).(color.NRGBA64)
379 cr[0][i+0] = uint8(c.R >> 8)
380 cr[0][i+1] = uint8(c.R)
381 cr[0][i+2] = uint8(c.G >> 8)
382 cr[0][i+3] = uint8(c.G)
383 cr[0][i+4] = uint8(c.B >> 8)
384 cr[0][i+5] = uint8(c.B)
385 cr[0][i+6] = uint8(c.A >> 8)
386 cr[0][i+7] = uint8(c.A)
392 f := filter(&cr, pr, bpp)
394 // Write the compressed bytes.
395 _, err = zw.Write(cr[f])
400 // The current row for y is the previous row for y+1.
401 pr, cr[0] = cr[0], pr
406 // Write the actual image data to one or more IDAT chunks.
407 func (e *encoder) writeIDATs() {
412 bw, e.err = bufio.NewWriterSize(e, 1<<15)
416 e.err = writeImage(bw, e.m, e.cb)
423 func (e *encoder) writeIEND() { e.writeChunk(e.tmp[0:0], "IEND") }
425 // Encode writes the Image m to w in PNG format. Any Image may be encoded, but
426 // images that are not image.NRGBA might be encoded lossily.
427 func Encode(w io.Writer, m image.Image) os.Error {
428 // Obviously, negative widths and heights are invalid. Furthermore, the PNG
429 // spec section 11.2.2 says that zero is invalid. Excessively large images are
431 mw, mh := int64(m.Bounds().Dx()), int64(m.Bounds().Dy())
432 if mw <= 0 || mh <= 0 || mw >= 1<<32 || mh >= 1<<32 {
433 return FormatError("invalid image size: " + strconv.Itoa64(mw) + "x" + strconv.Itoa64(mw))
440 var pal color.Palette
441 // cbP8 encoding needs PalettedImage's ColorIndexAt method.
442 if _, ok := m.(image.PalettedImage); ok {
443 pal, _ = m.ColorModel().(color.Palette)
448 switch m.ColorModel() {
449 case color.GrayModel:
451 case color.Gray16Model:
453 case color.RGBAModel, color.NRGBAModel, color.AlphaModel:
468 _, e.err = io.WriteString(w, pngHeader)
472 e.maybeWritetRNS(pal)