Creating PNG file

Hi everyone
I have made a .png file with paint on windows named source. I want to make a white png file with golang name destination and replace some its pixels with the source. I created the image like below:

destinationImage := image.NewNRGBA(image.Rect(0,0,1920,1080))
for x := 0; x < int(1920); x++ {
for y := 0; y < int(1080); y++ {
destinationImage.Set(x, y, color.White)
}
}
f, _ := os.Create(“Path of my File”)
png.Encode(f, destinationImage)
f.Close()

First of all, is there better method to create a white PNG file? As you see I had to manually set all pixels to white.
Secondly, I use sdl2/img library to manipulate the pixels, like this:

sourceImage,err := img.Load(“Path to source”)
destinationImage,err := img.Load(“Path to destination”)
sourcePixels := sourceImage.Pixels()
destinationPixels := destinationImage.Pixels()

Here I see len(sourcePixels) is 1920x1080x4 and len(destinationPixels) is 1920x1080x3, so when I create the image with paint each pixel has 4 value but when I create the image with Golang each pixel has 3 value, Why is that and how to solve it?

Hi. The difference between 1920x1080x4 and 1920x1080x3 I think is because 4 is ARGB where A is an alpha channel and 3 is just RGB with no alfa channel.

Hi
But as you see I’m using NewNRGBA which must create a RGBA image.

Hi. Tested myself and read the source of the methods also:

https://golang.org/src/image/png/writer.go#L613 tests if the image is opaque (no pixels with alfa-level other than 0xff) and if so it uses cbTC8 (color bitdepth True Color 8-bit) which doesn’t write the alfa channel https://golang.org/src/image/png/writer.go#L386

So this is why your image with only white opaque pixels are stored as 1920x1080x3

1 Like

I gave up on this and changed my algorithm, But you are right, I changed the color.White to a non-opaque color and the pixels became 4 value, but how should some one deal with an opaque color? I also had some other issues that decided to change my algorithm but thanks for replying.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.