Debian Codegraph @

src/pygame_sdl2/image.pyx

raw
1 # Copyright 2014 Patrick Dawson <[email protected]>
2 #
3 # This software is provided 'as-is', without any express or implied
4 # warranty. In no event will the authors be held liable for any damages
5 # arising from the use of this software.
6 #
7 # Permission is granted to anyone to use this software for any purpose,
8 # including commercial applications, and to alter it and redistribute it
9 # freely, subject to the following restrictions:
10 #
11 # 1. The origin of this software must not be misrepresented; you must not
12 # claim that you wrote the original software. If you use this software
13 # in a product, an acknowledgment in the product documentation would be
14 # appreciated but is not required.
15 # 2. Altered source versions must be plainly marked as such, and must not be
16 # misrepresented as being the original software.
17 # 3. This notice may not be removed or altered from any source distribution.
18
19 from sdl2 cimport *
20 from sdl2_image cimport *
21 from pygame_sdl2.surface cimport *
22 from pygame_sdl2.rwobject cimport to_rwops
23
24 from pygame_sdl2.error import error
25 from pygame_sdl2.compat import bytes_, unicode_, filesystem_encode
26
27 import sys
28 import os
29 import pygame_sdl2
30
31
32 cdef int image_formats = 0
33
34 def init():
35 # Attempt to initialize everything. Only fail loudly if all formats fail
36 global image_formats
37 image_formats = IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG | IMG_INIT_TIF | IMG_INIT_WEBP | IMG_INIT_JXL | IMG_INIT_AVIF)
38 if image_formats == 0:
39 raise error()
40
41 init()
42
43 # Make it possible for python to check individual formats
44 INIT_JPG = IMG_INIT_JPG
45 INIT_PNG = IMG_INIT_PNG
46 INIT_TIF = IMG_INIT_TIF
47 INIT_WEBP = IMG_INIT_WEBP
48 INIT_JXL = IMG_INIT_JXL
49 INIT_AVIF = IMG_INIT_AVIF
50
51 def has_init(int flags):
52 return (flags & image_formats) == flags
53
54 def quit(): # @ReservedAssignment
55 IMG_Quit()
56
57 cdef process_namehint(namehint):
58 # Accepts "foo.png", ".png", or "png"
59
60 if not isinstance(namehint, bytes_):
61 namehint = namehint.encode("ascii", "replace")
62
63 if not namehint:
64 return b''
65
66 ext = os.path.splitext(namehint)[1]
67 if not ext:
68 ext = namehint
69 if ext[0] == b'.':
70 ext = ext[1:]
71
72 return ext.upper()
73
74 def load(fi, namehint="", size=None):
75 """
76 `size`
77 A width, height tuple that specifies the size the image is loaded
78 at. This is only supported for SVG images.
79 """
80
81 cdef SDL_Surface *img
82
83 cdef SDL_RWops *rwops
84 cdef char *ftype
85
86 cdef int width
87 cdef int height
88
89 # IMG_Load_RW can't load TGA images.
90 if isinstance(fi, str):
91 if fi.lower().endswith('.tga'):
92 namehint = "TGA"
93
94 rwops = to_rwops(fi)
95
96 if namehint == "":
97 with nogil:
98 img = IMG_Load_RW(rwops, 1)
99
100 else:
101 namehint = process_namehint(namehint)
102 ftype = namehint
103
104 if namehint == b".SVG" and size is not None:
105 width, height = size
106
107 with nogil:
108 img = IMG_LoadSizedSVG_RW(rwops, width, height)
109
110 SDL_RWclose(rwops)
111
112 else:
113
114 with nogil:
115 img = IMG_LoadTyped_RW(rwops, 1, ftype)
116
117 if img == NULL:
118 raise error()
119
120 cdef Surface surf = Surface(())
121 surf.take_surface(img)
122
123 if img.format.BitsPerPixel == 32:
124 return surf
125
126 cdef int n = 0
127 has_alpha = False
128
129 if img.format.Amask:
130 has_alpha = True
131 elif (img.format.format >> 24) & SDL_PIXELTYPE_INDEX1:
132 has_alpha = True
133 elif img.format.palette != NULL:
134 # Check for non-opaque palette colors.
135 while n < img.format.palette.ncolors:
136 if img.format.palette.colors[n].a != 255:
137 has_alpha = True
138 break
139 n += 1
140
141 try:
142 if has_alpha:
143 return surf.convert_alpha()
144 else:
145 return surf.convert()
146 except error:
147 return surf
148
149 cdef extern from "write_jpeg.h":
150 int Pygame_SDL2_SaveJPEG(SDL_Surface *, char *, int) nogil
151
152 cdef extern from "write_png.h":
153 int Pygame_SDL2_SavePNG(const char *, SDL_Surface *, int) nogil
154
155 def save(Surface surface not None, filename, compression=-1):
156
157 if not isinstance(filename, unicode_):
158 filename = filename.decode(sys.getfilesystemencoding())
159
160 ext = os.path.splitext(filename)[1]
161 ext = ext.upper()
162 ext = ext.encode("utf-8")
163 err = 0
164
165 utf8_filename = filename.encode("utf-8")
166
167 cdef char *fn = utf8_filename
168 cdef SDL_RWops *rwops
169 cdef int compression_level = compression
170
171 if ext == b'.PNG':
172 with nogil:
173 err = Pygame_SDL2_SavePNG(fn, surface.surface, compression_level)
174 elif ext == b'.BMP':
175 rwops = to_rwops(filename, "wb")
176 with nogil:
177 err = SDL_SaveBMP_RW(surface.surface, rwops, 1)
178 elif ext == b".JPG" or ext == b".JPEG":
179 with nogil:
180 err = Pygame_SDL2_SaveJPEG(surface.surface, fn, compression_level)
181 else:
182 raise ValueError("Unsupported format: %s" % ext)
183
184 if err != 0:
185 raise error()
186
187 def get_extended():
188 # This may be called before init.
189 return True