首页 > 解决方案 > 更改像素值,保存并再次读取返回原始颜色

问题描述

我想将像素的所有蓝色值更改为 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)
}

标签: imagegodraw

解决方案


我找到了我的问题的答案。问题是,我正在解码 jpeg 图像,我从这个 stackoverflow 问题中发现 JPEG 图像会损失质量(因此,像素值会在此过程中被修改):当质量设置为 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)

推荐阅读