I want to change all Blue values of pixels to 255, if it is equal to 20. I read the source image, draw.Draw it to new image.RGBA, so that i can modify pixels.
But, when I take output image(after executing the program) and feed it as the input, and put a debug point inside the IF block, and run program in debug mode, i see in multiple points debugger stops inside there. Which means, I am not correctly modifying image.
Can anyone tell me, how can I modify pixels and save correctly? Thanks a lot
func changeOnePixelInImage() {
imgPath := "./source.png"
f, err := os.Open(imgPath)
check(err)
defer f.Close()
sourceImage, _, err := image.Decode(f)
size := sourceImage.Bounds().Size()
destImage := image.NewRGBA(sourceImage.Bounds())
draw.Draw(destImage, sourceImage.Bounds(), sourceImage, image.Point{}, draw.Over)
for x := 0; x < size.X; x++ {
for y := 0; y < size.Y; y++ {
pixel := sourceImage.At(x, y)
originalColor := color.RGBAModel.Convert(pixel).
(color.RGBA)
b := originalColor.B
if b == 20 {
b = 255 // <--- then i swap source and destination paths, and debug this line
}
c := color.RGBA{
R: originalColor.R,
G: originalColor.G,
B: b,
A: originalColor.A,
}
destImage.SetRGBA(x, y, c)
}
}
ext := filepath.Ext(imgPath)
newImagePath := fmt.Sprintf("%s/dest%s", filepath.Dir(imgPath), ext)
fg, err := os.Create(newImagePath)
check(err)
defer fg.Close()
err = jpeg.Encode(fg, destImage, &jpeg.Options{100})
check(err)
}
I found the answer to my question. The thing is, I was Decoding jpeg image, and I found out that JPEG images loss quality(so, pixel values are modified during the process) from this stackoverflow question: Is JPEG lossless when quality is set to 100?
So, I should have used PNG images.(and even though I am using source.png
as source image, it was actually jpg image :/)
So i changes last lines to:
if ext != ".png" {
panic("cannot do my thing with jpg images, since they get compressed")
}
err = png.Encode(fg, destImage)