all repos — mgba @ 0e40168a1b6b2e661babc1e9a8e0f87b65dbe02c

mGBA Game Boy Advance Emulator

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):
16        self.width = width
17        self.height = height
18        self.stride = stride
19        self.constitute()
20
21    def constitute(self):
22        if self.stride <= 0:
23            self.stride = self.width
24        self.buffer = ffi.new("color_t[{}]".format(self.stride * self.height))
25
26    def savePNG(self, f):
27        p = png.PNG(f)
28        success = p.writeHeader(self)
29        success = success and p.writePixels(self)
30        p.writeClose()
31        return success
32
33    if 'PImage' in globals():
34        def toPIL(self):
35            return PImage.frombytes("RGBX", (self.width, self.height), ffi.buffer(self.buffer), "raw",
36                                    "RGBX", self.stride * 4)
37
38def u16ToU32(c):
39    r = c & 0x1F
40    g = (c >> 5) & 0x1F
41    b = (c >> 10) & 0x1F
42    a = (c >> 15) & 1
43    abgr = r << 3
44    abgr |= g << 11
45    abgr |= b << 19
46    abgr |= (a * 0xFF) << 24
47    return abgr
48
49def u32ToU16(c):
50    r = (c >> 3) & 0x1F
51    g = (c >> 11) & 0x1F
52    b = (c >> 19) & 0x1F
53    a = c >> 31
54    abgr = r
55    abgr |= g << 5
56    abgr |= b << 10
57    abgr |= a << 15
58    return abgr
59
60if ffi.sizeof("color_t") == 2:
61    def colorToU16(c):
62        return c
63
64    colorToU32 = u16ToU32
65
66    def u16ToColor(c):
67        return c
68
69    u32ToColor = u32ToU16
70else:
71    def colorToU32(c):
72        return c
73
74    colorToU16 = u32ToU16
75
76    def u32ToColor(c):
77        return c
78
79    u16ToColor = u16ToU32