Using the Color package to create a new color value with RGB?

I am trying to create a new Color object using the RGB values ​​that I have in the variables:

http://golang.org/pkg/image/color/


 package main import ( "fmt" "image" _ "image/gif" _ "image/jpeg" _ "image/png" "os" ) func main() { reader, err := os.Open("test-image.jpg") if err != nil { fmt.Fprintf(os.Stderr, "%v\n", err) } image, _, err := image.Decode(reader) if err != nil { fmt.Fprintf(os.Stderr, "%s", err) } bounds := image.Bounds() for i := 0; i <= bounds.Max.X; i++ { for j := 0; j <= bounds.Max.Y; j++ { pixel := image.At(i, j) if i == 0 && j == 0 { red, green, blue, _ := pixel.RGBA() averaged := (red + green + blue) / 3 // This FromRGBA function DOES NOT EXIST! grayColor := Color.FromRGBA(averaged, averaged, averaged, 1) // Then I could do something like: grayColor.RGBA() // This would work since it a type Color. } } } } 

I cannot find any Function package that generates a new Color object based on rgba values.

Any recommendations?

+6
source share
2 answers

Types in the image/color package have exported fields, so you can create them directly. For your example, you can create a color value with:

 grayColor := color.Gray16{Y: uint16(averaged)} 

(The values red , green and blue are in the range 0..0xffff , so implementing a 16-bit gray seems appropriate).

+1
source

image.Color is actually an interface. You can use any structure that satisfies it. Even your own structures.

For example, you can use image.Gary:

 grayColor := image.Gray{averaged} 

or your own grayColor:

 type MyGray struct { y uint32 } func (gray *MyGray) FromRGBA(r, g, b, a uint32) { gray.y = (r + g + b) / 3 } func (gray *MyGray) RGBA() (r, g, b, a uint32) { // to satisfy image.Color return gray.y, gray.y, gray.y, 1 } grayColor := &MyGray{} grayColor.FromRGBA(pixel.RGBA()) grayColor.RGBA() // blablabla 
+1
source

All Articles