为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
沧海一幻觉 2022-06-27 17:31:03
我想将像素的所有蓝色值更改为 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)}
查看完整描述

1 回答

?
千巷猫影

TA贡献1829条经验 获得超7个赞

我找到了我的问题的答案。问题是,我正在解码 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)


查看完整回答
反对 回复 2022-06-27
  • 1 回答
  • 0 关注
  • 115 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号