登录
首页 >  Golang >  Go问答

改变像素值,保存并再次读取返回原始颜色

来源:stackoverflow

时间:2024-04-23 18:03:36 262浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《改变像素值,保存并再次读取返回原始颜色》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

我想将像素的所有蓝色值更改为 255(如果等于 20)。 我读取源图像,绘制。将其绘制到新图像.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 问题中发现 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)

到这里,我们也就讲完了《改变像素值,保存并再次读取返回原始颜色》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>