package pixel import "image/color" var ( MonochromeModel color.Model = color.ModelFunc(monochromeModel) ) // ToGrayBits converts a color to a n-bit grayscale color. func ToGrayBits(c color.Color, n uint8) uint16 { r, g, b, _ := c.RGBA() if n < 1 { return 0 // no color } else if n > 16 { n = 16 // most that will fit } // Shift values to fit n bits. s := 32 - n // These coefficients (the fractions 0.299, 0.587 and 0.114) are the same // as those given by the JFIF specification and used by func RGBToYCbCr in // image/color/ycbcr.go. // // Note that 19595 + 38470 + 7471 equals 65536. // // The 28 is 16 + 8 + n. The 16 is the same as used in RGBToYCbCr. The 8 + n is // because the return value is n-bit color, not 16 bit color. return uint16((19595*r + 38470*g + 7471*b + 1<<15) >> s) } // Monochrome color. type Monochrome uint8 // Monochrome color names. const ( Off Monochrome = iota On ) func (c Monochrome) RGBA() (r, g, b, a uint32) { if c == 0 { return 0, 0, 0, 0 } return 0xffff, 0xffff, 0xffff, 0xffff } func monochromeModel(c color.Color) color.Color { if _, ok := c.(Monochrome); ok { return c } if ToGrayBits(c, 1) == 0 { return Off } return On }