我用作image.png的图片是:
用254运行我的程序时,它工作,输出是:
这是我的代码.如果我将254更改为255,则输出文件将变为完全空(大小为0字节):
package main import "fmt" import "os" import "bufio" import "image/png" import "image" func main() { f,_ := os.Open("image.png") im,_ := png.Decode(bufio.NewReader(f)) img := im.(*image.RGBA) s := img.Bounds().Size() w := s.X h := s.Y fmt.Println(w,h) newPix := make([]uint8,len(img.Pix)) iy := 0 for ; iy < h; iy++ { ix := 0 for ; ix < w; ix++ { i := img.PixOffset(ix,iy) r := img.Pix[i+0] g := img.Pix[i+1] b := img.Pix[i+2] a := img.Pix[i+3] var max uint8 = 254 /*255*/ newPix[i+0] = uint8(max - r) newPix[i+1] = uint8(max - g) newPix[i+2] = uint8(max - b) newPix[i+3] = uint8(max - a) } } newImg := image.NewRGBA(img.Bounds()) newImg.Pix = newPix o,_ := os.Create("out.png") defer o.Close() png.Encode(bufio.NewWriter(o),newImg) fmt.Println("DONE") }
为什么这样,我该如何解决? 255仍然是uint8所以它应该工作…
我发现
a discussion on the golang-nuts group之前出现过这个问题.
原文链接:https://www.f2er.com/go/242073.html基本上,输出太小,无法自动触发写入器刷新.手动刷新编写器(在任何情况下都推荐)可以解决问题.
package main import "fmt" import "os" import "bufio" import "image/png" import "image" func main() { f,iy) r := img.Pix[i+0] g := img.Pix[i+1] b := img.Pix[i+2] a := img.Pix[i+3] var max uint8 = 255 newPix[i+0] = uint8(max - r) newPix[i+1] = uint8(max - g) newPix[i+2] = uint8(max - b) newPix[i+3] = uint8(max - a) } } newImg := image.NewRGBA(img.Bounds()) newImg.Pix = newPix o,_ := os.Create("out.png") defer o.Close() writer := bufio.NewWriter(o) png.Encode(writer,newImg) writer.Flush() fmt.Println("DONE") }
关于忽略错误的正常警告适用.