更改单个像素的颜色 - Golang图像

问题描述 投票:10回答:3

我想打开jpeg图像文件,对其进行编码,更改一些像素颜色,然后将其保存原样。

我想做这样的事情

imgfile, err := os.Open("unchanged.jpeg")
defer imgfile.Close()
if err != nil {
    fmt.Println(err.Error())
}

img,err := jpeg.Decode(imgfile)
if err != nil {
    fmt.Println(err.Error())
}
img.Set(0, 0, color.RGBA{85, 165, 34, 1})
img.Set(1,0,....)

outFile, _ := os.Create("changed.jpeg")
defer outFile.Close()
jpeg.Encode(outFile, img, nil)

我只是无法想出一个有效的解决方案,因为我在编码图像文件后得到的默认图像类型没有Set方法。

任何人都可以解释如何做到这一点?非常感谢。

image go draw
3个回答
14
投票

成功解码image.Decode()(以及jpeg.Decode()等特定解码函数)返回值image.Imageimage.Image是一个定义图像只读视图的界面:它不提供更改/绘制图像的方法。

image包提供了几个image.Image实现,允许您更改/绘制图像,通常使用Set(x, y int, c color.Color)方法。

然而,image.Decode()并不保证返回的图像将是image包中定义的任何图像类型,或者甚至图像的动态类型具有Set()方法(它可能,但不能保证)。注册的自定义图像解码器可能会返回一个image.Image值作为自定义实现(意味着不是image包中定义的图像类型)。

如果(动态类型)图像确实有Set()方法,您可以使用type assertion并使用其Set()方法绘制它。这是如何做到的:

type Changeable interface {
    Set(x, y int, c color.Color)
}

imgfile, err := os.Open("unchanged.jpg")
if err != nil {
    panic(err.Error())
}
defer imgfile.Close()

img, err := jpeg.Decode(imgfile)
if err != nil {
    panic(err.Error())
}

if cimg, ok := img.(Changeable); ok {
    // cimg is of type Changeable, you can call its Set() method (draw on it)
    cimg.Set(0, 0, color.RGBA{85, 165, 34, 255})
    cimg.Set(0, 1, color.RGBA{255, 0, 0, 255})
    // when done, save img as usual
} else {
    // No luck... see your options below
}

如果图像没有Set()方法,您可以通过实现实现image.Image的自定义类型来选择“覆盖其视图”,但在其At(x, y int) color.Color方法(返回/提供像素的颜色)中,您将返回新的颜色将设置图像是否可更改,并返回原始图像的像素,您不会更改图像。

使用嵌入最简单地实现image.Image接口,因此您只需要实现所需的更改。这是如何做到的:

type MyImg struct {
    // Embed image.Image so MyImg will implement image.Image
    // because fields and methods of Image will be promoted:
    image.Image
}

func (m *MyImg) At(x, y int) color.Color {
    // "Changed" part: custom colors for specific coordinates:
    switch {
    case x == 0 && y == 0:
        return color.RGBA{85, 165, 34, 255}
    case x == 0 && y == 1:
        return color.RGBA{255, 0, 0, 255}
    }
    // "Unchanged" part: the colors of the original image:
    return m.Image.At(x, y)
}

使用它:非常简单。像你一样加载图像,但保存时,提供我们的MyImg类型的值,它将在编码器询问时提供改变的图像内容(颜色):

jpeg.Encode(outFile, &MyImg{img}, nil)

如果你必须改变许多像素,那么在At()方法中包含所有像素是不切实际的。为此我们可以扩展我们的MyImg以使我们的Set()实现存储我们想要改变的像素。示例实现:

type MyImg struct {
    image.Image
    custom map[image.Point]color.Color
}

func NewMyImg(img image.Image) *MyImg {
    return &MyImg{img, map[image.Point]color.Color{}}
}

func (m *MyImg) Set(x, y int, c color.Color) {
    m.custom[image.Point{x, y}] = c
}

func (m *MyImg) At(x, y int) color.Color {
    // Explicitly changed part: custom colors of the changed pixels:
    if c := m.custom[image.Point{x, y}]; c != nil {
        return c
    }
    // Unchanged part: colors of the original image:
    return m.Image.At(x, y)
}

使用它:

// Load image as usual, then

my := NewMyImg(img)
my.Set(0, 0, color.RGBA{85, 165, 34, 1})
my.Set(0, 1, color.RGBA{255, 0, 0, 255})

// And when saving, save 'my' instead of the original:
jpeg.Encode(outFile, my, nil)

如果你必须改变很多像素,那么创建一个支持改变其像素的新图像可能更有利可图,例如image.RGBA,在其上绘制原始图像,然后继续更改您想要的像素。

要将图像绘制到另一个图像上,可以使用image/draw包。

cimg := image.NewRGBA(img.Bounds())
draw.Draw(cimg, img.Bounds(), img, image.Point{}, draw.Over)

// Now you have cimg which contains the original image and is changeable
// (it has a Set() method)
cimg.Set(0, 0, color.RGBA{85, 165, 34, 255})
cimg.Set(0, 1, color.RGBA{255, 0, 0, 255})

// And when saving, save 'cimg' of course:
jpeg.Encode(outFile, cimg, nil)

以上代码仅供演示。在“真实”图像中,Image.Bounds()可能会返回一个不在(0;0)点开始的矩形,在这种情况下,需要进行一些调整才能使其工作。


2
投票

图像解码返回image interface,其具有Bounds方法以获得图像像素宽度和高度。

img, _, err := image.Decode(imgfile)
if err != nil {
    fmt.Println(err.Error())
}
size := img.Bounds().Size()

一旦你有了宽度和高度,就可以用两个嵌套的for循环迭代像素(一个用于x,另一个用于y坐标)。

for x := 0; x < size.X; x++ {
    for y := 0; y < size.Y; y++ {
        color := color.RGBA{
            uint8(255 * x / size.X),
            uint8(255 * y / size.Y),
            55,
            255}
        m.Set(x, y, color)
    }
}

完成图像处理后,您可以对文件进行编码。但是因为image.Image没有Set方法,你可以创建一个新的RGBA图像,它返回一个RGBA结构,你可以在其上使用Set方法。

m := image.NewRGBA(image.Rect(0, 0, width, height))
outFile, err := os.Create("changed.jpg")
if err != nil {
    log.Fatal(err)
}
defer outFile.Close()
png.Encode(outFile, m)

0
投票

image.Image默认是不可变的,但draw.Image是可变的。

如果你对draw.Image进行类型转换,那应该会给你一个Set方法

img.(draw.Image).Set(0,0, color.RGBA{85, 165, 34, 1})
© www.soinside.com 2019 - 2024. All rights reserved.