Golang newbie here, I'm trying to create a script that takes a png, gets the rgb values of each pixel, formats it into css colors and pushes them into a slice so that I can then have it create the png image in html & css (stupid project I know)
I'm able to do most things but for some reason, the colors aren't correct. I have as input a 2px image.
The colors are as follows (left to right): [black, white, black, white]
So I would expect to get this [0 0 0 255 | 255 255 255 255 | 0 0 0 255 | 255 255 255 255]
I'm getting these values instead: [254 0 0 0| 254 254 255 2 | 2 2 255 1 | 1 1 255 254]
I'm not sure what I'm doing wrong
package main
import (
"fmt"
"image"
"image/draw"
"image/png"
"log"
"math"
"os"
)
func imageLoader(path string) *os.File {
image.RegisterFormat("png", "png", png.Decode, png.DecodeConfig)
file, err := os.Open(path)
if err != nil {
fmt.Println("Error: File could not be opened")
os.Exit(1)
}
return file
}
func main() {
pngImage := imageLoader("./2pxImg.png")
img, err := png.Decode(pngImage)
if err != nil {
log.Fatal(err)
}
rect := img.Bounds()
rgbaArr := image.NewRGBA(rect)
draw.Draw(rgbaArr, rect, img, rect.Min, draw.Src)
var rgba [4]uint8
var hexArr = make([]string, 0, len(rgbaArr.Pix)/4)
rgbaIdx := 0
for idx, colorVal := range rgbaArr.Pix {
rgba[rgbaIdx] = colorVal
rgbaIdx += 1
// modulus 4 because rgba has 4 values
if idx%4 == 0 {
rgbaIdx = 0
hexArr = append(hexArr, rgbaToCssColor(&rgba, true))
}
}
}
func rgbaToCssColor(rgba *[4]uint8, isRgb bool) string {
fmt.Printf("%v, %v, %v, %v\n", rgba[0], rgba[1], rgba[2], rgba[3])
if isRgb {
alpha := math.Floor((float64(rgba[3])/255)*10) / 10
return fmt.Sprintf("rgba(%v, %v, %v, %v)", rgba[0], rgba[1], rgba[2], alpha)
}
return fmt.Sprintf("#%02x%02x%02x%02x", rgba[0], rgba[1], rgba[2], rgba[3])
}
I have used this stackoverflow answer to get the rgba values https://stackoverflow.com/a/33198436/9118002