问题描述
我想将所有蓝色像素值更改为255(如果等于20)。 我读取了源图像,绘制。将其绘制到新的image.RGBA,以便可以修改像素。
但是,当我获取输出图像(执行程序后)并将其作为输入,并在IF块中放入调试点,并在调试模式下运行程序时,我看到调试器在多个点停在那里。这意味着我没有正确修改图像。
谁能告诉我,如何修改像素并正确保存?非常感谢
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)
}
解决方法
我找到了问题的答案。 问题是,我正在解码jpeg图像,并且从以下stackoverflow问题Is JPEG lossless when quality is set to 100?
中发现JPEG图像质量下降(因此,像素值在此过程中被修改)。因此,我应该使用PNG图像。(即使我使用source.png
作为源图像,它实际上也是jpg图像:/)
所以我将最后几行更改为:
if ext != ".png" {
panic("cannot do my thing with jpg images,since they get compressed")
}
err = png.Encode(fg,destImage)