Using the Color package to create new Color from RGB value?

709 views
Skip to first unread message

stapia.g...@gmail.com

unread,
Feb 27, 2014, 7:07:19 PM2/27/14
to golan...@googlegroups.com
http://stackoverflow.com/questions/22083460/using-the-color-package-to-create-new-color-from-rgb-value

I'm trying to create a new `Color` object using RGB values I have in variables:


---

    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's a type Color.
    
    }
    }
    }
    }

I can't seem to find any package Function that generates a new Color object given rgba values. 

Any recommendations?

Stephen Gutekanst

unread,
Feb 28, 2014, 2:38:12 AM2/28/14
to golan...@googlegroups.com, stapia.g...@gmail.com
grayColor := color.RGBA{averaged, averaged, averaged, 1}
type RGBA struct {
        R, G, B, A uint8
}

Matt Harden

unread,
Feb 28, 2014, 2:57:57 PM2/28/14
to Stephen Gutekanst, golang-nuts, stapia.g...@gmail.com
If you want the grayColor to be a variable of type Color, then

grayColor := color.RGBA{averaged, averaged, averaged, 1}.(color.Color)

If you want the gray to be a better visual approximation of the given color, don't use the average of the RGB components. Use GrayModel (or GrayModel16):

grayColor := color.GrayModel.Convert(pixel)



--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Reply all
Reply to author
Forward
0 new messages