【问题标题】:changing pixel value, saving and reading again returns the original color更改像素值,保存并再次读取返回原始颜色
【发布时间】:2020-09-18 05:22:41
【问题描述】:

如果等于 20,我想将像素的所有蓝色值更改为 255。 我读取源图像,将其绘制到新的 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.Encode的源码,不太明白,不过好像是根据jpeg.Options.Quality来缩放图片的。这就是为什么我设置为 100(最大),如果不是 100 可能是压缩图像

标签: image go draw


【解决方案1】:

我找到了我的问题的答案。 问题是,我正在解码 jpeg 图像,我从这个 stackoverflow 问题中发现 JPEG 图像质量下降(因此,像素值在此过程中被修改):Is JPEG lossless when quality is set to 100?

所以,我应该使用 PNG 图像。(即使我使用 source.png 作为源图像,它实际上是 jpg 图像:/)

所以我将最后几行更改为:

if ext != ".png" {
    panic("cannot do my thing with jpg images, since they get compressed")
}
err = png.Encode(fg, destImage)

【讨论】:

    猜你喜欢
    • 2013-06-25
    • 1970-01-01
    • 2015-07-21
    • 1970-01-01
    • 2020-05-08
    • 2012-04-23
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    相关资源
    最近更新 更多