unexpected color drawn in image

51 views
Skip to first unread message

Dustin

unread,
Feb 12, 2012, 4:35:12 AM2/12/12
to golan...@googlegroups.com
I've got this code that should yield a subtle grey with a touch of red that's throwing out mad cyan.  Can anyone offer a clue as to what's happening here?

Changing the alpha from 130 to 131 reveals the correct color.


package main

import (
"image"
"image/color"
"image/png"
"log"
"os"
)

func main() {
bounds := image.Rect(0, 0, 1024, 1024)
i := image.NewRGBA(bounds)

color := color.RGBA{131, 127, 127, 130}

for x := bounds.Min.X; x < bounds.Max.X; x++ {
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
i.Set(x, y, color)
}
}

f, err := os.Create("test.png")
if err != nil {
log.Fatalf("error creating file: %v", err)
}
png.Encode(f, i)
}

si guy

unread,
Feb 12, 2012, 4:50:39 AM2/12/12
to golan...@googlegroups.com
RGBA is supposed to be alpha-premultiplied (according to source)
I think you want to be using NRGBA and setting A to 255, or doing the pre-multiplying yourself. http://www.gimp.org/docs/plug-in/appendix-alpha.html

Nigel Tao

unread,
Feb 12, 2012, 4:50:53 AM2/12/12
to Dustin, golan...@googlegroups.com
On 12 February 2012 20:35, Dustin <dsal...@gmail.com> wrote:
> I've got this code that should yield a subtle grey with a touch of red
> that's throwing out mad cyan.  Can anyone offer a clue as to what's
> happening here?
>
> color := color.RGBA{131, 127, 127, 130}

Go's color.RGBA is alpha-premultiplied. The R, G and B values should
be <= the A value. This format is more efficient for image
composition.

The PNG format is non-alpha-premultiplied. When you pass an invalid
color.RGBA value, then the output can look unexpected.

If you want to use the PNG color model, either use color.RGBA{66, 64,
64, 130} or use color.NRGBA instead of color.RGBA.

Dustin

unread,
Feb 12, 2012, 5:25:02 AM2/12/12
to golan...@googlegroups.com
I found the NRGBA thing on my own shortly after starting this thread, but I think I've got a few clues here to help me understand what this all means.  For my purposes, NRGBA will do what I want in the meantime.  Thanks for the pointers.
Reply all
Reply to author
Forward
0 new messages