src/platform/python/mgba/image.py (view raw)
1# Copyright (c) 2013-2016 Jeffrey Pfau
2#
3# This Source Code Form is subject to the terms of the Mozilla Public
4# License, v. 2.0. If a copy of the MPL was not distributed with this
5# file, You can obtain one at http://mozilla.org/MPL/2.0/.
6from ._pylib import ffi, lib
7from . import png
8
9try:
10 import PIL.Image as PImage
11except ImportError:
12 pass
13
14class Image:
15 def __init__(self, width, height, stride=0, alpha=False):
16 self.width = width
17 self.height = height
18 self.stride = stride
19 self.alpha = alpha
20 self.constitute()
21
22 def constitute(self):
23 if self.stride <= 0:
24 self.stride = self.width
25 self.buffer = ffi.new("color_t[{}]".format(self.stride * self.height))
26
27 def savePNG(self, f):
28 p = png.PNG(f, mode=png.MODE_RGBA if self.alpha else png.MODE_RGB)
29 success = p.writeHeader(self)
30 success = success and p.writePixels(self)
31 p.writeClose()
32 return success
33
34 if 'PImage' in globals():
35 def toPIL(self):
36 type = "RGBA" if self.alpha else "RGBX"
37 return PImage.frombytes(type, (self.width, self.height), ffi.buffer(self.buffer), "raw",
38 type, self.stride * 4)
39
40def u16ToU32(c):
41 r = c & 0x1F
42 g = (c >> 5) & 0x1F
43 b = (c >> 10) & 0x1F
44 a = (c >> 15) & 1
45 abgr = r << 3
46 abgr |= g << 11
47 abgr |= b << 19
48 abgr |= (a * 0xFF) << 24
49 return abgr
50
51def u32ToU16(c):
52 r = (c >> 3) & 0x1F
53 g = (c >> 11) & 0x1F
54 b = (c >> 19) & 0x1F
55 a = c >> 31
56 abgr = r
57 abgr |= g << 5
58 abgr |= b << 10
59 abgr |= a << 15
60 return abgr
61
62if ffi.sizeof("color_t") == 2:
63 def colorToU16(c):
64 return c
65
66 colorToU32 = u16ToU32
67
68 def u16ToColor(c):
69 return c
70
71 u32ToColor = u32ToU16
72else:
73 def colorToU32(c):
74 return c
75
76 colorToU16 = u32ToU16
77
78 def u32ToColor(c):
79 return c
80
81 u16ToColor = u16ToU32