From 8dfa16a47cced0b8206a5fba0b16ce5fe36e4b79 Mon Sep 17 00:00:00 2001 From: Vittorio Giovara Date: Tue, 14 Jul 2015 01:59:35 +0100 Subject: [PATCH] Add non-premultiplied BGRA support --- README.md | 2 ++ bgra.go | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 bgra.go diff --git a/README.md b/README.md index 1a38f28..be8c40e 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,8 @@ I was quite surprised when I found that the Go image package does not have any RGB image types without alpha. Also, it lacks grayscale with alpha. So I decided to write them myself. +Then I noticed also BGRA is missing, so I added that too. + ### API Documentation ### There are 2 packages: diff --git a/bgra.go b/bgra.go new file mode 100644 index 0000000..2350a68 --- /dev/null +++ b/bgra.go @@ -0,0 +1,89 @@ +package image2 + +import ( + "image" + "image/color" +) + +/*****************************************************************************/ + +type NBGRA struct { + Pix []uint8 + Stride int + Rect image.Rectangle +} + +func (p *NBGRA) ColorModel() color.Model { + return color.NRGBAModel +} + +func (p *NBGRA) Bounds() image.Rectangle { + return p.Rect +} + +func (p *NBGRA) At(x, y int) color.Color { + if !(image.Point{x, y}.In(p.Rect)) { + return color.NRGBA{} + } + + i := p.PixOffset(x, y) + return color.NRGBA{ + B: p.Pix[i + 0], + G: p.Pix[i + 1], + R: p.Pix[i + 2], + A: p.Pix[i + 3], + } +} + +func (p *NBGRA) PixOffset(x, y int) int { + return (y - p.Rect.Min.Y) * p.Stride + (x - p.Rect.Min.X) * 4 +} + +func (p *NBGRA) Set(x, y int, c color.Color) { + if !(image.Point{x, y}.In(p.Rect)) { + return + } + + i := p.PixOffset(x, y) + c1 := color.NRGBAModel.Convert(c).(color.NRGBA) + p.Pix[i + 0] = c1.B + p.Pix[i + 1] = c1.G + p.Pix[i + 2] = c1.R + p.Pix[i + 3] = c1.A +} + +func (p *NBGRA) SetNRGBA(x, y int, c color.NRGBA) { + if !(image.Point{x, y}.In(p.Rect)) { + return + } + i := p.PixOffset(x, y) + p.Pix[i + 0] = c.B + p.Pix[i + 1] = c.G + p.Pix[i + 2] = c.R + p.Pix[i + 3] = c.A +} + +func (p *NBGRA) SubImage(r image.Rectangle) image.Image { + r = r.Intersect(p.Rect) + if r.Empty() { + return &NBGRA{} + } + i := p.PixOffset(r.Min.X, r.Min.Y) + return &NBGRA{ + Pix: p.Pix[i:], + Stride: p.Stride, + Rect: r, + } +} + +func NewNBGRA(r image.Rectangle) *NBGRA { + w, h := r.Dx(), r.Dy() + buf := make([]uint8, 4 * w * h) + return &NBGRA{ + Pix: buf, + Stride: w * 4, + Rect: r, + } +} + +/*****************************************************************************/