For the record, this is a bad way to use bufio.Writer. You should always
flush the buffer before closing the underlying writer or you will be
missing data. I suspect that your "working" JPEG and GIF images from your
original posted code are incomplete files too (just somewhat less
incomplete than 0-bytes).

As for the backgrounds, PNG is the only format that supports an alpha
channel, so the default pixel values of (0,0,0,0) will produce a
transparent background (0 alpha), while JPEG and GIF images will ignore the
alpha values and thus use the color of black (0,0,0). The white you see for
PNG, is either the result of the surface you are drawing it on, or how your
renderer shows transparent pixels when it doesn't handle an alpha channel.

If you want a black background, you should fill your image with (0,0,0,255)
before starting. Also if writing PNG files, if you use image.NRGBA (non
premultiplied alpha images), then encoding them to png files should be
faster and lossless as they don't need to be converted first; although for
non-transparent images the conversion should be lossless as well.
On Wednesday, December 4, 2013 11:20:55 PM UTC-8, Graham MacDonald wrote:

Yes, that's it. If I flush the writer, the png is written. Curiously
though, with this example, the png has a white background, while the jpeg
and gif both have black backgrounds.

On Wednesday, 4 December 2013 23:58:24 UTC, Graham MacDonald wrote:


I've got some simple code to write out the same image in 3 different
formats: png, jpeg and gif. The image is correctly written for jpeg and
gif, but I get a zero length file for the png. Any idea why this would
happen, or does it look like a bug?

Here's the code:

package main

import (

func main() {
img := image.NewRGBA(image.Rect(0, 0, 640, 480))

c := color.RGBA{255, 0, 0, 255}
draw.Draw(img, image.Rect(10, 10, 100, 100), &image.Uniform{c},
image.ZP, draw.Src)

if imgFilePng, err := os.Create("red.png"); err != nil {
fmt.Println("Png error: ", err)
} else {
defer imgFilePng.Close()
png.Encode(bufio.NewWriter(imgFilePng), img)

if imgFileGif, err := os.Create("red.gif"); err != nil {
fmt.Println("Gif error: ", err)
} else {
defer imgFileGif.Close()
gif.Encode(bufio.NewWriter(imgFileGif), img, &gif.Options{})

if imgFileJpeg, err := os.Create("red.jpeg"); err != nil {
fmt.Println("Jpeg error: ", err)
} else {
defer imgFileJpeg.Close()
jpeg.Encode(bufio.NewWriter(imgFileJpeg), img,

You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Search Discussions

Discussion Posts


Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 7 of 8 | next ›
Discussion Overview
groupgolang-nuts @
postedDec 4, '13 at 11:58p
activeDec 5, '13 at 2:18p



site design / logo © 2021 Grokbase