更改像素颜色,将背景改为白色,黑色高亮
func TestName1(t *testing.T) {
source := "./img.png" //输⼊图⽚
target := "./result.png" //输出图⽚
ff, _ := ioutil.ReadFile(source) //读取⽂件
bbb := bytes.NewBuffer(ff)
m, _, _ := image.Decode(bbb)
bounds := m.Bounds()
dx := bounds.Dx()
dy := bounds.Dy()
newRgba := image.NewRGBA(bounds) //new ⼀个新的图⽚
for i := 0; i < dx; i++ {
for j := 0; j < dy; j++ {
colorRgb := m.At(i, j)
r, g, b, a := colorRgb.RGBA()
r_uint8 := uint8(r >> 8) //转换为 255 值
g_uint8 := uint8(g >> 8)
b_uint8 := uint8(b >> 8)
a_uint8 := uint8(a >> 8)
if r_uint8 > 100 && g_uint8 > 100 && b_uint8 > 100 {
newRgba.SetRGBA(i, j, color.RGBA{255, 255, 255, a_uint8})
} else {
newRgba.SetRGBA(i, j, color.RGBA{0, 0, 0, a_uint8})
}
}
}
f, _ := os.Create(target)
defer f.Close()
encode(source, f, newRgba)
}
//图⽚编码写⼊
func encode(inputName string, file *os.File, rgba *image.RGBA) {
if strings.HasSuffix(inputName, "jpg") || strings.HasSuffix(inputName, "jpeg") {
jpeg.Encode(file, rgba, nil)
} else if strings.HasSuffix(inputName, "png") {
png.Encode(file, rgba)
} else if strings.HasSuffix(inputName, "gif") {
gif.Encode(file, rgba, nil)
} else {
fmt.Errorf("不⽀持的图⽚格式")
}
}
效果图