From 2fae8a5012e99f87367152186a52de8e359dd127 Mon Sep 17 00:00:00 2001 From: Sander Schobers Date: Sat, 10 Feb 2018 09:12:42 +0100 Subject: [PATCH] Native Go image is now loaded directly as Allegro bitmap. - Previous implementation used a temporary file (PNG). --- allegro5/bitmap.go | 45 ++++++++++++++++++++++++++------------------- 1 file changed, 26 insertions(+), 19 deletions(-) diff --git a/allegro5/bitmap.go b/allegro5/bitmap.go index eb1d0ee..f7aeebf 100644 --- a/allegro5/bitmap.go +++ b/allegro5/bitmap.go @@ -5,11 +5,10 @@ package allegro5 import "C" import ( + "errors" "fmt" "image" - "image/png" - "io/ioutil" - "os" + "image/color" "unsafe" ) @@ -62,27 +61,35 @@ func NewBitmap(width, height int) (*Bitmap, error) { return &Bitmap{b, width, height}, nil } -func exportToPng(im image.Image) (string, error) { - tmp, err := ioutil.TempFile("", "galleg") - if nil != err { - return "", err - } - defer tmp.Close() - err = png.Encode(tmp, im) - if nil != err { - return "", err - } - return tmp.Name(), nil -} - // NewBitmapFromImage creates a new bitmap starting from a Go native image (image.Image) func NewBitmapFromImage(im image.Image) (*Bitmap, error) { - path, err := exportToPng(im) + var bnd = im.Bounds() + width, height := bnd.Dx(), bnd.Dy() + bmp, err := NewBitmap(width, height) if nil != err { return nil, err } - defer os.Remove(path) - return LoadBitmap(path) + row := make([]uint8, width*4) + rgn := C.al_lock_bitmap(bmp.bitmap, C.ALLEGRO_PIXEL_FORMAT_ABGR_8888, C.ALLEGRO_LOCK_WRITEONLY) + if nil == rgn { + bmp.Destroy() + return nil, errors.New("unable to lock bitmap") + } + data := (*[1 << 30]uint8)(rgn.data) + offset := 0 + for y := 0; y < height; y++ { + for x := 0; x < width; x++ { + pix := color.RGBAModel.Convert(im.At(x, y)).(color.RGBA) + row[x*4] = pix.R + row[x*4+1] = pix.G + row[x*4+2] = pix.B + row[x*4+3] = pix.A + } + copy(data[offset:], row) + offset += int(rgn.pitch) + } + C.al_unlock_bitmap(bmp.bitmap) + return bmp, nil } // LoadBitmap tries to load the image at the specified path as a bitmap