Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

            }
        }
    }
}

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

Any recommendations?

like image 749
sergserg Avatar asked Feb 28 '14 00:02

sergserg


1 Answers

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

For example, you could 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
like image 141
mikespook Avatar answered Sep 20 '22 17:09

mikespook