package pixel import ( "image" "image/color" ) // Gray4 represents a 4-bit grayscale color. type Gray4 struct { Y uint8 } func (c Gray4) RGBA() (r, g, b, a uint32) { y := uint32(c.Y & 0x0f) y |= y << 4 y |= y << 8 return y, y, y, 0xffff } var Gray4Model color.Model = color.ModelFunc(gray4Model) func gray4Model(c color.Color) color.Color { if _, ok := c.(Gray4); ok { return c } r, g, b, _ := c.RGBA() // 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 // ycbcr.go. // // Note that 19595 + 38470 + 7471 equals 65536. // // The 28 is 16 + 8 + 4. The 16 is the same as used in RGBToYCbCr. The 8 + 4 is // because the return value is 4 bit color, not 16 bit color. y := (19595*r + 38470*g + 7471*b + 1<<15) >> 28 return Gray4{uint8(y)} } // ImageGray4 contains 4-bit grayscale pixels. type ImageGray4 struct { Pix []byte Rect image.Rectangle Stride int } func NewImageGray4(r image.Rectangle) *ImageGray4 { var ( w, h = r.Dx(), r.Dy() size = w * h / 2 pix = make([]byte, size) ) return &ImageGray4{pix, r, w / 2} } func (i *ImageGray4) ColorModel() color.Model { return Gray4Model } func (i *ImageGray4) Bounds() image.Rectangle { return i.Rect } func (i *ImageGray4) At(x, y int) color.Color { if !(image.Point{x, y}.In(i.Rect)) { return Gray4{0} } o := (y*i.Stride + x) >> 1 if x&1 == 0 { // even x is stored in the high bits return Gray4{i.Pix[o] >> 4} } return Gray4{i.Pix[o] & 0x0f} } func (i *ImageGray4) Set(x, y int, c color.Color) { if !(image.Point{x, y}.In(i.Rect)) { return } o := (y*i.Stride + x) >> 1 if x&1 == 0 { // even x is stored in the high bits i.Pix[o] = i.Pix[o]&0x0f | c.(Gray4).Y<<4 } else { i.Pix[o] = i.Pix[o]&0xf0 | c.(Gray4).Y } }