I want to open jpeg image file, encode it, change some pixel colors, and then save it back as it was.
I\'d like to do something like this
imgfile, er
The image decode returns an image interface which has a Bounds method to obtain the image pixel width and height.
img, _, err := image.Decode(imgfile)
if err != nil {
fmt.Println(err.Error())
}
size := img.Bounds().Size()
Once you have the width and height you can iterate over the pixels with two nested for loops (one for the x and one for y coordinate).
for x := 0; x < size.X; x++ {
for y := 0; y < size.Y; y++ {
color := color.RGBA{
uint8(255 * x / size.X),
uint8(255 * y / size.Y),
55,
255}
m.Set(x, y, color)
}
}
Once your are done with the image manipulation you can encode the file. But because image.Image does not have Set method, you can create a new RGBA image, which returns an RGBA struct, on which you can use the Set method.
m := image.NewRGBA(image.Rect(0, 0, width, height))
outFile, err := os.Create("changed.jpg")
if err != nil {
log.Fatal(err)
}
defer outFile.Close()
png.Encode(outFile, m)