dongxing8766 2015-05-14 01:42
浏览 185

使用image.Image或* image.RGBA的Set()方法

I am doing some practice with the Go image package with my free time this summer.

package main

import (

    "os"
    "image"
    "image/png"
    "image/color"
    "log"
    "fmt"
    "reflect"

)

func main(){

    file , err := os.OpenFile("C:/Sources/go3x3.png", os.O_RDWR, os.FileMode(0777))
    if err != nil {
        log.Fatal(err)
    }

    img , err := png.Decode(file)
    if err != nil {
        log.Fatal(err)
    }


    img.At(0,0).RGBA()
    fmt.Println("type:", reflect.TypeOf(img))

    m := image.NewRGBA(image.Rect(0, 0, 640, 480))
    fmt.Println("type:", reflect.TypeOf(m))
    m.Set(5, 5, color.RGBA{255, 0, 0, 255})
    img.Set(0, 0, color.RGBA{136, 0, 21, 255})
}

The problem here is when I run it with the img.Set commented out I get this result

type: *image.RGBA
type: *image.RGBA

but when it's uncommented I get an error saying

img.Set undefined (type image.Image has no field or method Set)

I'm assuming I'm using reflect wrong, I'm still fully grasping the whole interface and type definitions in Go.

  • 写回答

3条回答 默认 最新

  • dongluanjie8678 2015-05-14 02:06
    关注

    reflect.TypeOf(img) gives you the reflection type of the value in the interface img, if its an interface. In this case, img is an interface, an image.Image which contains an *image.RGBA.

    You can fix your code by converting img to an *image.RGBA, or more robustly, define an interface type with the right Set method, and convert img to that (the draw.Image interface in "image/draw" works perfectly for this, as noted by @DaveC). The interface type is preferable if you aren't sure that png.Decode will always give you an *image.RGBA for the .png files you have.

    img.(*image.RGBA).Set(0, 0, color.RGBA{136, 0, 21, 255})
    

    or

    type Setter interface {
        Set(x, y int, c color.Color)
    }
    
    img.(Setter).Set(0, 0, color.RGBA{136, 0, 21, 255})
    

    or (probably best):

    import "image/draw"
    
    ...
    
    img.(draw.Image).Set(0, 0, color.RGBA{136, 0, 21, 255})
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog