Native Go image is now loaded directly as Allegro bitmap.
- Previous implementation used a temporary file (PNG).
This commit is contained in:
parent
6dd358365e
commit
2fae8a5012
@ -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
|
||||
|
Loading…
Reference in New Issue
Block a user