media_utils

Wrapper over PIL. (Used to be a wrapper over SDL2)

  1"""Wrapper over PIL. (Used to be a wrapper over SDL2)"""
  2
  3from utils import *
  4
  5class Color(Tuple):
  6    """An (r,g,b,a) color tuple"""
  7
  8    r = g = b = ...; a = 0xff
  9
 10    @staticmethod
 11    def gray(c):
 12        return Color(c, c, c)
 13
 14    def set_a(m, a):
 15        return Color(m.r, m.g, m.b, a)
 16
 17class PixelFormat(Enum):
 18    rgba8 = "RGBA"
 19    bgra8 = ("RGBA", "BGRA")
 20    rgb8 = "RGB"
 21    i8 = "P"
 22
 23    @property
 24    def _pil_fmt(m):
 25        return m.value[0] if isinstance(m.value, tuple) else m.value
 26    @property
 27    def _pil_raw_fmt(m):
 28        return m.value[1] if isinstance(m.value, tuple) else m.value
 29
 30    @property
 31    def bpp(m):
 32        if m == m.i8:
 33            return 8
 34        else:
 35            return 32
 36
 37def _to_pil_tuple(obj):
 38    if obj is None:
 39        return None
 40    elif len(obj) == 2:
 41        return tuple(obj)
 42    elif len(obj) == 4:
 43        x, y, w, h = obj
 44        return x, y, x + w, y + h
 45    else:
 46        fail(obj)
 47
 48def _pil_module():
 49    try:
 50        from PIL import Image # type: ignore
 51    except ImportError:
 52        throw("You need pillow (or PIL) to read/write PNGs (do 'python -m pip install pillow')")
 53    return Image
 54
 55class Image:
 56    @staticmethod
 57    def load(f, fmt=None):
 58        surf = Image(_pil_module().open(f))
 59        if e(fmt) and surf.format != fmt:
 60            surf = surf.convert(fmt)
 61        return surf
 62
 63    @staticmethod
 64    def create(w, h, fmt=PixelFormat.rgba8):
 65        return Image(_pil_module().new(fmt._pil_fmt, (w, h)), fmt)
 66    
 67    @staticmethod
 68    def from_data(w, h, fmt, data, pitch=None):
 69        return Image(_pil_module().frombytes(fmt._pil_fmt, (w, h), data, "raw", fmt._pil_raw_fmt, pitch or 0), fmt)
 70
 71    def __init__(m, pil, fmt=None):
 72        m.pil = pil
 73        m.fmt = fmt
 74    
 75    def to_data(m, fmt=None, flip=False):
 76        if fmt is None:
 77            fmt = m.format
 78        return m.pil.tobytes("raw", fmt._pil_raw_fmt, 0, -1 if flip else 1)
 79
 80    def save(m, dest=None, format="png", **format_opts):
 81        if dest is None:
 82            dest = BytesIO()
 83            m.save(dest, format, **format_opts)
 84            return dest.getvalue()
 85        
 86        m.pil.save(dest, format, **format_opts)
 87
 88    def convert(m, fmt):
 89        return Image(m.pil.convert(fmt._pil_fmt))
 90
 91    @property
 92    def width(m):
 93        return m.pil.width
 94    @property
 95    def height(m):
 96        return m.pil.height
 97    @property
 98    def size(m):
 99        return Point(m.width, m.height)
100
101    def resize(m, size):
102        return Image(m.pil.resize(size, _pil_module().NEAREST))
103    def scale(m, factor):
104        return m.resize(m.size * factor)
105
106    @property
107    def alpha(m):
108        return Image(m.pil.getchannel('A'))
109
110    @property
111    def format(m):
112        if m.fmt is None:
113            m.fmt = PixelFormat(m.pil.mode)
114        return m.fmt
115
116    @property
117    def pixels(m):
118        return m.pil.load()
119
120    def copy(m):
121        return Image(m.pil.copy())
122    
123    def slice(m, rect):
124        return Image(m.pil.crop(_to_pil_tuple(rect)))
125
126    def draw(m, src, dest=None, srcrect=None):
127        src = src.pil.crop(_to_pil_tuple(srcrect)) if e(srcrect) else src.pil
128        m.pil.alpha_composite(src, _to_pil_tuple(dest))
129    
130    def fill(m, color, dest=None, mask=None):
131        m.pil.paste(color, _to_pil_tuple(dest), mask.pil if mask else None)
132
133    @writeonly_property
134    def palette(m, pal):
135        m.pil.putpalette(pal.raw, "RGBA")
136
137Surface = Image # old SDL2-style name
138
139class Palette: # (pil's ImagePalette doesn't seem fit for purpose)
140    @staticmethod
141    def create(n):
142        return Palette([0] * (4 * n))
143
144    def __init__(m, raw):
145        m.raw = raw
146    
147    def __len__(m):
148        return len(m.raw) // 4
149
150    def __getitem__(m, i):
151        return m.raw[4 * i : 4 * (i + 1)]
152    
153    def __setitem__(m, i, v):
154        m.raw[4 * i : 4 * (i + 1)] = v
155
156    def to_surface(m):
157        return Image.from_data(len(m), 1, PixelFormat.rgba8, bytes(m.raw))
class Color(utils.Tuple):
 6class Color(Tuple):
 7    """An (r,g,b,a) color tuple"""
 8
 9    r = g = b = ...; a = 0xff
10
11    @staticmethod
12    def gray(c):
13        return Color(c, c, c)
14
15    def set_a(m, a):
16        return Color(m.r, m.g, m.b, a)

An (r,g,b,a) color tuple

a

Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])

@staticmethod
def gray(c):
11    @staticmethod
12    def gray(c):
13        return Color(c, c, c)
def set_a(m, a):
15    def set_a(m, a):
16        return Color(m.r, m.g, m.b, a)
r

Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])

g

Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])

b

Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])

class PixelFormat(utils.Enum):
18class PixelFormat(Enum):
19    rgba8 = "RGBA"
20    bgra8 = ("RGBA", "BGRA")
21    rgb8 = "RGB"
22    i8 = "P"
23
24    @property
25    def _pil_fmt(m):
26        return m.value[0] if isinstance(m.value, tuple) else m.value
27    @property
28    def _pil_raw_fmt(m):
29        return m.value[1] if isinstance(m.value, tuple) else m.value
30
31    @property
32    def bpp(m):
33        if m == m.i8:
34            return 8
35        else:
36            return 32

If a class has Enum as a baseclass, it's transformed into an enum. All non-private attributes of the class other than functions and descriptors become enum members. Atributes with a value of ... receive values automatically. Inherited classes behave like regular classes unless they have Enum as a direct baseclass. Advanced: ExcludeAttr/IncludeAttr, _values keyword parameter Atributes with a name ending with _ can be referred to without the _.

PixelFormat(value)
172        def __init__(m, value):
173            if value in full_value_name_map:
174                m.value = value
175            elif value in full_name_value_map:
176                m.value = full_name_value_map[value]
177            else:
178                raise ValueError(f"{value} not value of {cls_name}")
bpp
31    @property
32    def bpp(m):
33        if m == m.i8:
34            return 8
35        else:
36            return 32
value
class Image:
 56class Image:
 57    @staticmethod
 58    def load(f, fmt=None):
 59        surf = Image(_pil_module().open(f))
 60        if e(fmt) and surf.format != fmt:
 61            surf = surf.convert(fmt)
 62        return surf
 63
 64    @staticmethod
 65    def create(w, h, fmt=PixelFormat.rgba8):
 66        return Image(_pil_module().new(fmt._pil_fmt, (w, h)), fmt)
 67    
 68    @staticmethod
 69    def from_data(w, h, fmt, data, pitch=None):
 70        return Image(_pil_module().frombytes(fmt._pil_fmt, (w, h), data, "raw", fmt._pil_raw_fmt, pitch or 0), fmt)
 71
 72    def __init__(m, pil, fmt=None):
 73        m.pil = pil
 74        m.fmt = fmt
 75    
 76    def to_data(m, fmt=None, flip=False):
 77        if fmt is None:
 78            fmt = m.format
 79        return m.pil.tobytes("raw", fmt._pil_raw_fmt, 0, -1 if flip else 1)
 80
 81    def save(m, dest=None, format="png", **format_opts):
 82        if dest is None:
 83            dest = BytesIO()
 84            m.save(dest, format, **format_opts)
 85            return dest.getvalue()
 86        
 87        m.pil.save(dest, format, **format_opts)
 88
 89    def convert(m, fmt):
 90        return Image(m.pil.convert(fmt._pil_fmt))
 91
 92    @property
 93    def width(m):
 94        return m.pil.width
 95    @property
 96    def height(m):
 97        return m.pil.height
 98    @property
 99    def size(m):
100        return Point(m.width, m.height)
101
102    def resize(m, size):
103        return Image(m.pil.resize(size, _pil_module().NEAREST))
104    def scale(m, factor):
105        return m.resize(m.size * factor)
106
107    @property
108    def alpha(m):
109        return Image(m.pil.getchannel('A'))
110
111    @property
112    def format(m):
113        if m.fmt is None:
114            m.fmt = PixelFormat(m.pil.mode)
115        return m.fmt
116
117    @property
118    def pixels(m):
119        return m.pil.load()
120
121    def copy(m):
122        return Image(m.pil.copy())
123    
124    def slice(m, rect):
125        return Image(m.pil.crop(_to_pil_tuple(rect)))
126
127    def draw(m, src, dest=None, srcrect=None):
128        src = src.pil.crop(_to_pil_tuple(srcrect)) if e(srcrect) else src.pil
129        m.pil.alpha_composite(src, _to_pil_tuple(dest))
130    
131    def fill(m, color, dest=None, mask=None):
132        m.pil.paste(color, _to_pil_tuple(dest), mask.pil if mask else None)
133
134    @writeonly_property
135    def palette(m, pal):
136        m.pil.putpalette(pal.raw, "RGBA")
Image(pil, fmt=None)
72    def __init__(m, pil, fmt=None):
73        m.pil = pil
74        m.fmt = fmt
@staticmethod
def load(f, fmt=None):
57    @staticmethod
58    def load(f, fmt=None):
59        surf = Image(_pil_module().open(f))
60        if e(fmt) and surf.format != fmt:
61            surf = surf.convert(fmt)
62        return surf
@staticmethod
def create(w, h, fmt=PixelFormat.rgba8):
64    @staticmethod
65    def create(w, h, fmt=PixelFormat.rgba8):
66        return Image(_pil_module().new(fmt._pil_fmt, (w, h)), fmt)
@staticmethod
def from_data(w, h, fmt, data, pitch=None):
68    @staticmethod
69    def from_data(w, h, fmt, data, pitch=None):
70        return Image(_pil_module().frombytes(fmt._pil_fmt, (w, h), data, "raw", fmt._pil_raw_fmt, pitch or 0), fmt)
def to_data(m, fmt=None, flip=False):
76    def to_data(m, fmt=None, flip=False):
77        if fmt is None:
78            fmt = m.format
79        return m.pil.tobytes("raw", fmt._pil_raw_fmt, 0, -1 if flip else 1)
def save(m, dest=None, format='png', **format_opts):
81    def save(m, dest=None, format="png", **format_opts):
82        if dest is None:
83            dest = BytesIO()
84            m.save(dest, format, **format_opts)
85            return dest.getvalue()
86        
87        m.pil.save(dest, format, **format_opts)
def convert(m, fmt):
89    def convert(m, fmt):
90        return Image(m.pil.convert(fmt._pil_fmt))
width
92    @property
93    def width(m):
94        return m.pil.width
height
95    @property
96    def height(m):
97        return m.pil.height
size
 98    @property
 99    def size(m):
100        return Point(m.width, m.height)
def resize(m, size):
102    def resize(m, size):
103        return Image(m.pil.resize(size, _pil_module().NEAREST))
def scale(m, factor):
104    def scale(m, factor):
105        return m.resize(m.size * factor)
alpha
107    @property
108    def alpha(m):
109        return Image(m.pil.getchannel('A'))
format
111    @property
112    def format(m):
113        if m.fmt is None:
114            m.fmt = PixelFormat(m.pil.mode)
115        return m.fmt
pixels
117    @property
118    def pixels(m):
119        return m.pil.load()
def copy(m):
121    def copy(m):
122        return Image(m.pil.copy())
def slice(m, rect):
124    def slice(m, rect):
125        return Image(m.pil.crop(_to_pil_tuple(rect)))
def draw(m, src, dest=None, srcrect=None):
127    def draw(m, src, dest=None, srcrect=None):
128        src = src.pil.crop(_to_pil_tuple(srcrect)) if e(srcrect) else src.pil
129        m.pil.alpha_composite(src, _to_pil_tuple(dest))
def fill(m, color, dest=None, mask=None):
131    def fill(m, color, dest=None, mask=None):
132        m.pil.paste(color, _to_pil_tuple(dest), mask.pil if mask else None)
palette

Method decorator that turns it into a write-only property

Surface = <class 'Image'>
class Palette:
140class Palette: # (pil's ImagePalette doesn't seem fit for purpose)
141    @staticmethod
142    def create(n):
143        return Palette([0] * (4 * n))
144
145    def __init__(m, raw):
146        m.raw = raw
147    
148    def __len__(m):
149        return len(m.raw) // 4
150
151    def __getitem__(m, i):
152        return m.raw[4 * i : 4 * (i + 1)]
153    
154    def __setitem__(m, i, v):
155        m.raw[4 * i : 4 * (i + 1)] = v
156
157    def to_surface(m):
158        return Image.from_data(len(m), 1, PixelFormat.rgba8, bytes(m.raw))
Palette(raw)
145    def __init__(m, raw):
146        m.raw = raw
@staticmethod
def create(n):
141    @staticmethod
142    def create(n):
143        return Palette([0] * (4 * n))
def to_surface(m):
157    def to_surface(m):
158        return Image.from_data(len(m), 1, PixelFormat.rgba8, bytes(m.raw))