duangan2307 2016-04-12 12:33
浏览 295
已采纳

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

I want to open jpeg image file, encode it, change some pixel colors, and then save it back as it was.

I'd like to do something like this

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)

I just can't come up with a working solution, since default image type that I get after encoding image-file doesn't have Set method.

Can anyone explain how to do this? Thanks a lot.

  • 写回答

3条回答 默认 最新

  • dopzc64662 2016-04-12 15:01
    关注

    On successful decoding image.Decode() (and also specific decoding functions like jpeg.Decode()) return a value of image.Image. image.Image is an interface which defines a read-only view of an image: it does not provide methods to change / draw on the image.

    The image package provides several image.Image implementations which allow you to change / draw on the image, usually with a Set(x, y int, c color.Color) method.

    image.Decode() however does not give you any guarantee that the returned image will be any of the image types defined in the image package, or even that the dynamic type of the image has a Set() method (it may, but no guarantee). Registered custom image decoders may return you an image.Image value being a custom implementation (meaning not an image type defined in the image package).

    If the (dynamic type of the) image does have a Set() method, you may use type assertion and use its Set() method to draw on it. This is how it can be done:

    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
    }
    

    If the image does not have a Set() method, you may choose to "override its view" by implementing a custom type which implements image.Image, but in its At(x, y int) color.Color method (which returns / supplies the colors of pixels) you return the new colors that you would set if the image would be changeable, and return the pixels of the original image where you would not change the image.

    Implementing the image.Image interface is easiest done by utilizing embedding, so you only need to implement the changes you want. This is how it can be done:

    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)
    }
    

    Using it: extremely simple. Load the image as you did, but when saving, provide a value of our MyImg type which will take care of providing the altered image content (colors) when it is asked by the encoder:

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

    If you have to change many pixels, it's not practical to include all in the At() method. For that we can extend our MyImg to have our Set() implementation which stores the pixels that we want to change. Example implementation:

    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)
    }
    

    Using it:

    // 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)
    

    If you have to change many pixels, then it might be more profitable to just create a new image which supports changing its pixels, e.g. image.RGBA, draw the original image on it and then proceed to change pixels you want to.

    To draw an image onto another, you can use the image/draw package.

    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)
    

    The above code is just for demonstration. In "real-life" images Image.Bounds() may return a rectangle that does not start at (0;0) point, in which case some adjustment would be needed to make it work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图