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 . import png
try:
import PIL.Image as PImage
except ImportError:
pass
class Image:
def __init__(self, width, height, stride=0):
self.width = width
self.height = height
self.stride = stride
self.constitute()
def __init__(self, width, height, stride=0):
self.width = width
self.height = height
self.stride = stride
self.constitute()
def constitute(self):
if self.stride <= 0:
self.stride = self.width
self.buffer = ffi.new("color_t[{}]".format(self.stride * self.height))
def constitute(self):
if self.stride <= 0:
self.stride = self.width
self.buffer = ffi.new("color_t[{}]".format(self.stride * self.height))
def savePNG(self, f):
p = png.PNG(f)
success = p.writeHeader(self)
success = success and p.writePixels(self)
p.writeClose()
return success
def savePNG(self, f):
p = png.PNG(f)
success = p.writeHeader(self)
success = success and p.writePixels(self)
p.writeClose()
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):
r = c & 0x1F
g = (c >> 5) & 0x1F
b = (c >> 10) & 0x1F
a = (c >> 15) & 1
abgr = r << 3
abgr |= g << 11
abgr |= b << 19
abgr |= (a * 0xFF) << 24
return abgr
r = c & 0x1F
g = (c >> 5) & 0x1F
b = (c >> 10) & 0x1F
a = (c >> 15) & 1
abgr = r << 3
abgr |= g << 11
abgr |= b << 19
abgr |= (a * 0xFF) << 24
return abgr
def u32ToU16(c):
r = (c >> 3) & 0x1F
g = (c >> 11) & 0x1F
b = (c >> 19) & 0x1F
a = c >> 31
abgr = r
abgr |= g << 5
abgr |= b << 10
abgr |= a << 15
return abgr
r = (c >> 3) & 0x1F
g = (c >> 11) & 0x1F
b = (c >> 19) & 0x1F
a = c >> 31
abgr = r
abgr |= g << 5
abgr |= b << 10
abgr |= a << 15
return abgr
if ffi.sizeof("color_t") == 2:
def colorToU16(c):
return c
def colorToU16(c):
return c
colorToU32 = u16ToU32
colorToU32 = u16ToU32
def u16ToColor(c):
return c
def u16ToColor(c):
return c
u32ToColor = u32ToU16
u32ToColor = u32ToU16
else:
def colorToU32(c):
return c
def colorToU32(c):
return c
colorToU16 = u32ToU16
colorToU16 = u32ToU16
def u32ToColor(c):
return c
def u32ToColor(c):
return c
u16ToColor = u16ToU32
u16ToColor = u16ToU32

View File

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