Python: Add PIL export

This commit is contained in:
Vicki Pfau 2017-06-14 17:28:01 -07:00
parent 732ed5fa4d
commit 0e40168a1b
2 changed files with 56 additions and 45 deletions

View File

@ -6,64 +6,74 @@
from ._pylib import ffi, lib from ._pylib import ffi, lib
from . import png from . import png
try:
import PIL.Image as PImage
except ImportError:
pass
class Image: class Image:
def __init__(self, width, height, stride=0): def __init__(self, width, height, stride=0):
self.width = width self.width = width
self.height = height self.height = height
self.stride = stride self.stride = stride
self.constitute() self.constitute()
def constitute(self): def constitute(self):
if self.stride <= 0: if self.stride <= 0:
self.stride = self.width self.stride = self.width
self.buffer = ffi.new("color_t[{}]".format(self.stride * self.height)) self.buffer = ffi.new("color_t[{}]".format(self.stride * self.height))
def savePNG(self, f): def savePNG(self, f):
p = png.PNG(f) p = png.PNG(f)
success = p.writeHeader(self) success = p.writeHeader(self)
success = success and p.writePixels(self) success = success and p.writePixels(self)
p.writeClose() p.writeClose()
return success return success
if 'PImage' in globals():
def toPIL(self):
return PImage.frombytes("RGBX", (self.width, self.height), ffi.buffer(self.buffer), "raw",
"RGBX", self.stride * 4)
def u16ToU32(c): def u16ToU32(c):
r = c & 0x1F r = c & 0x1F
g = (c >> 5) & 0x1F g = (c >> 5) & 0x1F
b = (c >> 10) & 0x1F b = (c >> 10) & 0x1F
a = (c >> 15) & 1 a = (c >> 15) & 1
abgr = r << 3 abgr = r << 3
abgr |= g << 11 abgr |= g << 11
abgr |= b << 19 abgr |= b << 19
abgr |= (a * 0xFF) << 24 abgr |= (a * 0xFF) << 24
return abgr return abgr
def u32ToU16(c): def u32ToU16(c):
r = (c >> 3) & 0x1F r = (c >> 3) & 0x1F
g = (c >> 11) & 0x1F g = (c >> 11) & 0x1F
b = (c >> 19) & 0x1F b = (c >> 19) & 0x1F
a = c >> 31 a = c >> 31
abgr = r abgr = r
abgr |= g << 5 abgr |= g << 5
abgr |= b << 10 abgr |= b << 10
abgr |= a << 15 abgr |= a << 15
return abgr return abgr
if ffi.sizeof("color_t") == 2: if ffi.sizeof("color_t") == 2:
def colorToU16(c): def colorToU16(c):
return c return c
colorToU32 = u16ToU32 colorToU32 = u16ToU32
def u16ToColor(c): def u16ToColor(c):
return c return c
u32ToColor = u32ToU16 u32ToColor = u32ToU16
else: else:
def colorToU32(c): def colorToU32(c):
return c return c
colorToU16 = u32ToU16 colorToU16 = u32ToU16
def u32ToColor(c): def u32ToColor(c):
return c return c
u16ToColor = u16ToU32 u16ToColor = u16ToU32

View File

@ -23,6 +23,7 @@ setup(name="${BINARY_NAME}",
packages=["mgba"], packages=["mgba"],
setup_requires=['cffi>=1.6'], setup_requires=['cffi>=1.6'],
install_requires=['cffi>=1.6', 'cached-property'], install_requires=['cffi>=1.6', 'cached-property'],
extras_require={'pil': ['Pillow>=2.3']},
cffi_modules=["_builder.py:ffi"], cffi_modules=["_builder.py:ffi"],
license="MPL 2.0", license="MPL 2.0",
classifiers=classifiers classifiers=classifiers