-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapngasm.py
More file actions
executable file
·595 lines (491 loc) · 20.2 KB
/
Copy pathapngasm.py
File metadata and controls
executable file
·595 lines (491 loc) · 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
#!/usr/bin/env python3
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Optional
if TYPE_CHECKING:
from numpy.typing import NDArray
from PIL import Image
from ._apngasm_python import APNGFrame # type: ignore
from ._apngasm_python import (APNGAsm, IAPNGAsmListener, create_frame_from_rgb,
create_frame_from_rgb_trns,
create_frame_from_rgba)
class APNGAsmBinder:
"""
Python class for binding apngasm library
"""
# https://www.w3.org/TR/PNG-Chunks.html
color_type_dict = {0: "L", 2: "RGB", 3: "P", 4: "LA", 6: "RGBA"}
def __init__(self):
self.apngasm = APNGAsm()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb): # type: ignore
self.apngasm.reset()
def frame_pixels_as_pillow(
self, frame: int, new_value: Optional[Image.Image] = None
) -> Optional[Image.Image]:
"""
Get/Set the raw pixel data of frame, expressed as a Pillow object.
This should be set AFTER you set the width, height and color_type.
:param int frame: Target frame number.
:param Optional[PIL.Image.Image] new_value: If set, then the raw pixel data of
frame is set with this value.
:return: Pillow image object of the frame (get) or None (set)
:rtype: Optional[PIL.Image.Image]
"""
from numpy import array
from PIL import Image
if new_value:
self.apngasm.get_frames()[frame].pixels = array(new_value)
return None
else:
mode = self.color_type_dict[self.apngasm.get_frames()[frame].color_type]
return Image.frombytes( # type: ignore
mode,
(
self.apngasm.get_frames()[frame].width,
self.apngasm.get_frames()[frame].height,
),
self.apngasm.get_frames()[frame].pixels,
)
def frame_pixels_as_numpy(
self, frame: int, new_value: Optional[NDArray[Any]] = None
) -> Optional[NDArray[Any]]:
"""
Get/Set the raw pixel data of frame, expressed as a 3D numpy array.
This should be set AFTER you set the width, height and color_type.
:param int frame: Target frame number.
:param Optional[numpy.typing.NDArray[Any]] new_value: If set, then the
raw pixel data of frame is set with this value.
:return: 3D numpy array representation of
raw pixel data of frame (get) or None (set)
:rtype: Optional[numpy.typing.NDArray[Any]]
"""
from numpy import array
if new_value:
self.apngasm.get_frames()[frame].pixels = new_value
return None
else:
return array(self.apngasm.get_frames()[frame].pixels)
def frame_width(self, frame: int, new_value: Optional[int] = None) -> Optional[int]:
"""
Get/Set the width of frame.
:param int frame: Target frame number.
:param Optional[int] new_value: If set, then the width of frame
is set with this value.
:return: width (get) or None (set)
:rtype: Optional[int]
"""
if new_value:
self.apngasm.get_frames()[frame].width = new_value
return None
else:
return self.apngasm.get_frames()[frame].width
def frame_height(
self, frame: int, new_value: Optional[int] = None
) -> Optional[int]:
"""
Get/Set the height of frame.
:param int frame: Target frame number.
:param Optional[int] new_value: If set, then the height of frame
is set with this value.
:return: height (get) or None (set)
:rtype: Optional[int]
"""
if new_value:
self.apngasm.get_frames()[frame].height = new_value
return None
else:
return self.apngasm.get_frames()[frame].height
def frame_color_type(
self, frame: int, new_value: Optional[int] = None
) -> Optional[int]:
"""
Get/Set the color_type of frame.
0: Grayscale (Pillow mode='L')
2: RGB (Pillow mode='RGB')
3: Palette (Pillow mode='P')
4: Grayscale + Alpha (Pillow mode='LA')
6: RGBA (Pillow mode='RGBA')
:param int frame: Target frame number.
:param Optional[int] new_value: If set, then the color type of frame
is set with this value.
:return: color_type of frame (get) or None (set)
:rtype: Optional[int]
"""
if new_value:
self.apngasm.get_frames()[frame].color_type = new_value
return None
else:
return self.apngasm.get_frames()[frame].color_type
def frame_palette(
self, frame: int, new_value: Optional[NDArray[Any]] = None
) -> Optional[NDArray[Any]]:
"""
Get/Set the palette data of frame.
Only applies to 'P' mode Image (i.e. Not RGB, RGBA).
Expressed as 2D numpy array
in format of [[r0, g0, b0], [r1, g1, b1], ..., [r255, g255, b255]]
:param int frame: Target frame number.
:param Optional[numpy.typing.NDArray[Any]] new_value: If set, then
the palette data of frame is set with this value.
:return: 2D numpy array representation of
palette data of frame (get) or None (set)
:rtype: Optional[numpy.typing.NDArray[Any]]
"""
from numpy import array
if new_value:
self.apngasm.get_frames()[frame].palette = new_value
return None
else:
return array(self.apngasm.get_frames()[frame].palette)
def frame_transparency(
self, frame: int, new_value: Optional[NDArray[Any]] = None
) -> Optional[NDArray[Any]]:
"""
Get/Set the color [r, g, b] to be treated as transparent in the frame,
expressed as 1D numpy array.
For more info, refer to 'tRNS Transparency' in
http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html
:param int frame: Target frame number.
:param Optional[numpy.typing.NDArray[Any]] new_value: If set, then the
transparency of frame is set with this value.
:return: The color [r, g, b] to be treated as transparent
in the frame (get) or None (set)
:rtype: Optional[numpy.typing.NDArray[Any]]
"""
from numpy import array
if new_value:
self.apngasm.get_frames()[frame].transparency = new_value
return None
else:
return array(self.apngasm.get_frames()[frame].transparency)
def frame_palette_size(
self, frame: int, new_value: Optional[int] = None
) -> Optional[int]:
"""
Get/Set the palette data size of frame.
:param int frame: Target frame number.
:param Optional[int] new_value: If set, then the palette data size of frame
is set with this value.
:return: Palette data size of frame (get) or None (set)
:rtype: Optional[int]
"""
if new_value:
self.apngasm.get_frames()[frame].palette_size = new_value
return None
else:
return self.apngasm.get_frames()[frame].palette_size
def frame_transparency_size(
self, frame: int, new_value: Optional[int] = None
) -> Optional[int]:
"""
Get/Set the transparency data size of frame.
:param int frame: Target frame number.
:param Optional[int] new_value: If set, then the transparency data size of frame
is set with this value.
:return: Transparency data size of frame (get) or None (set)
:rtype: Optional[int]
"""
if new_value:
self.apngasm.get_frames()[frame].transparency_size = new_value
return None
else:
return self.apngasm.get_frames()[frame].transparency_size
def frame_delay_num(
self, frame: int, new_value: Optional[int] = None
) -> Optional[int]:
"""
Get/Set the nominator of the duration of frame.
Duration of time is delay_num / delay_den seconds.
:param int frame: Target frame number.
:param Optional[int] new_value: If set, then the nominator of the
duration of frame is set with this value.
:return: Nominator of the duration of frame.
:rtype: Optional[int]
"""
if new_value:
self.apngasm.get_frames()[frame].delay_num = new_value
return None
else:
return self.apngasm.get_frames()[frame].delay_num
def frame_delay_den(
self, frame: int, new_value: Optional[int] = None
) -> Optional[int]:
"""
Get/Set the denominator of the duration of frame.
Duration of time is delay_num / delay_den seconds.
:param int frame: Target frame number.
:param Optional[int] new_value: If set, then the denominator of the
duration of frame is set with this value.
:return: Denominator of the duration of frame.
:rtype: Optional[int]
"""
if new_value:
self.apngasm.get_frames()[frame].delay_den = new_value
return None
else:
return self.apngasm.get_frames()[frame].delay_den
def add_frame_from_file(
self, file_path: str, delay_num: int = 100, delay_den: int = 1000
) -> int:
"""
Adds a frame from a PNG file or frames from a APNG file to the frame vector.
:param str file_path: The relative or absolute path to an image file.
:param int delay_num: The delay numerator for this frame (defaults to 100).
:param int delay_den: The delay denominator for this frame (defaults to 1000).
:return: The new number of frames.
:rtype: int
"""
return self.apngasm.add_frame_from_file(
file_path=file_path, delay_num=delay_num, delay_den=delay_den
)
def add_frame_from_pillow(
self, pillow_image: Image.Image, delay_num: int = 100, delay_den: int = 1000
) -> int:
"""
Add a frame from Pillow image.
The frame duration is equal to delay_num / delay_den seconds.
Default frame duration is 100/1000 second, or 0.1 second.
:param PIL.Image.Image pillow_image: Pillow image object.
:param int delay_num: The delay numerator for this frame (defaults to 100).
:param int delay_den: The delay denominator for this frame (defaults to 1000).
:return: The new number of frames.
:rtype: int
"""
from numpy import array
if pillow_image.mode not in ("RGB", "RGBA"):
pillow_image = pillow_image.convert("RGBA")
return self.add_frame_from_numpy(
numpy_data=array(pillow_image),
width=pillow_image.width,
height=pillow_image.height,
mode=pillow_image.mode,
delay_num=delay_num,
delay_den=delay_den,
)
def add_frame_from_numpy(
self,
numpy_data: NDArray[Any],
width: Optional[int] = None,
height: Optional[int] = None,
trns_color: Optional[NDArray[Any]] = None,
mode: Optional[str] = None,
delay_num: int = 100,
delay_den: int = 1000,
) -> int:
"""
Add frame from numpy array.
The frame duration is equal to delay_num / delay_den seconds.
Default frame duration is 100/1000 second, or 0.1 second.
:param numpy.typing.NDArray[Any] numpy_data: The pixel data, expressed as
3D numpy array.
:param Optional[int] width: The width of the pixel data.
If not given, the 2nd dimension size of numpy_data is used.
:param Optional[int] height: The height of the pixel data.
If not given, the 1st dimension size of numpy_data is used.
:param Optional[str] mode: The color mode of data. Possible values are
RGB or RGBA. If not given, it is determined using the 3rd dimension size
of numpy_data.
:param Optional[numpy.typing.NDArray[Any]] trns_color: The color [r, g, b] to
be treated as transparent, expressed as 1D numpy array.
Only use if RGB mode.
:param int delay_num: The delay numerator for this frame (defaults to 100).
:param int delay_den: The delay denominator for this frame (defaults to 1000).
:return: The new number of frames.
:rtype: int
"""
from numpy import ndarray, shape
width = width if width else shape(numpy_data)[1]
height = height if height else shape(numpy_data)[0]
if not mode:
if len(shape(numpy_data)) == 3:
if shape(numpy_data)[2] == 3:
mode = "RGB"
elif shape(numpy_data)[2] == 4:
mode = "RGBA"
else:
raise TypeError(
"Cannot determine mode from numpy_data. "
"expected 3rd dimension size to be 3 (RGB) or 4 (RGBA). "
"The given numpy_data shape was "
f"{shape(numpy_data)}."
)
if mode == "RGB":
if isinstance(trns_color, ndarray):
frame = create_frame_from_rgb_trns(
pixels=numpy_data,
width=width,
height=height,
trns_color=trns_color,
delay_num=delay_num,
delay_den=delay_den,
)
else:
frame = create_frame_from_rgb(
pixels=numpy_data,
width=width,
height=height,
delay_num=delay_num,
delay_den=delay_den,
)
elif mode == "RGBA":
if isinstance(trns_color, ndarray):
raise TypeError(
"Cannot set trns_color on RGBA mode Pillow object. Must be RGB."
)
frame = create_frame_from_rgba(
pixels=numpy_data,
width=width,
height=height,
delay_num=delay_num,
delay_den=delay_den,
)
else:
raise TypeError(f"Invalid mode: {mode}. Must be RGB or RGBA.")
return self.apngasm.add_frame(frame)
def assemble(self, output_path: str) -> bool:
"""
Assembles and outputs an APNG file.
:param str output_path: The output file path.
:return: true if assemble completed succesfully.
:rtype: bool
"""
return self.apngasm.assemble(output_path)
def disassemble_as_numpy(self, file_path: str) -> list[NDArray[Any]]:
"""
Disassembles an APNG file to a list of frames, expressed as 3D numpy array.
:param str file_path: The file path to the PNG image to be disassembled.
:return: A list containing the frames of the disassembled PNG.
:rtype: list[numpy.typing.NDArray[Any]]
"""
from numpy import array
frames = self.apngasm.disassemble(file_path)
frames_numpy: list[NDArray[Any]] = []
for frame in frames:
frames_numpy.append(array(frame.pixels))
return frames_numpy
def disassemble_as_pillow(self, file_path: str) -> list[Image.Image]:
"""
Disassembles an APNG file to a list of frames, expressed as Pillow images.
:param str file_path: The file path to the PNG image to be disassembled.
:return: A list containing the frames of the disassembled PNG.
:rtype: list[PIL.Image.Image]
"""
from PIL import Image
frames = self.apngasm.disassemble(file_path)
frames_pillow: list[Image.Image] = []
for frame in frames:
mode = self.color_type_dict[frame.color_type]
frame_pillow = Image.frombytes( # type: ignore
mode, (frame.width, frame.height), frame.pixels
)
frames_pillow.append(frame_pillow)
return frames_pillow
def save_pngs(self, output_dir: str) -> bool:
"""
Saves individual PNG files of the frames in the frame vector.
:param str output_dir: The directory where the PNG fils will be saved.
:return: true if all files were saved successfully.
:rtype: bool
"""
return self.apngasm.save_pngs(output_dir)
def load_animation_spec(self, file_path: str) -> list[APNGFrame]:
"""
Loads an animation spec from JSON or XML.
Loaded frames are added to the end of the frame vector.
For more details on animation specs see:
https://github.com/Genshin/PhantomStandards
You probably won't need to use this function
:param str file_path: The path of JSON or XML file.
:return: A vector containing the loaded frames.
:rtype: list[apngasm_python._apngasm_python.APNGFrame]
"""
return self.apngasm.load_animation_spec(file_path)
def save_json(self, output_path: str, image_dir: str) -> bool:
"""
Saves a JSON animation spec file.
You probably won't need to use this function
:param str output_path: Path to save the file to.
:param str image_dir: Directory where frame files are to be saved
if not the same path as the animation spec.
:return: true if save was successful.
:rtype: bool
"""
return self.apngasm.save_json(output_path, image_dir)
def save_xml(self, output_path: str, image_dir: str) -> bool:
"""
Saves an XML animation spec file.
:param str filePath: Path to save the file to.
:param str image_dir: Directory where frame files are to be saved
if not the same path as the animation spec.
:return: true if save was successful.
:rtype: bool
"""
return self.apngasm.save_xml(output_path, image_dir)
def set_apngasm_listener(self, listener: Optional[IAPNGAsmListener] = None): # type: ignore
"""
Sets a listener.
You probably won't need to use this function.
:param Optional[apngasm_python._apngasm_python.IAPNGAsmListener] listener:
A pointer to the listener object. If the argument is None,
a default APNGAsmListener will be created and assigned.
"""
raise NotImplementedError("set_apngasm_listener is not implemented")
# return self.apngasm.set_apngasm_listener(listener)
def set_loops(self, loops: int = 0):
"""
Set loop count of animation.
:param int loops: Loop count of animation. If the argument is 0
a loop count is infinity.
"""
return self.apngasm.set_loops(loops)
def set_skip_first(self, skip_first: bool):
"""
Set flag of skip first frame.
:param bool skip_first: Flag of skip first frame.
"""
return self.apngasm.set_skip_first(skip_first)
def get_frames(self) -> list[APNGFrame]:
"""
Returns the frame vector.
:return: frame vector.
:rtype: list[apngasm_python._apngasm_python.APNGFrame]
"""
return self.apngasm.get_frames()
def get_loops(self) -> int:
"""
Returns the loop count.
:return: loop count.
:rtype: int
"""
return self.apngasm.get_loops()
def is_skip_first(self) -> bool:
"""
Returns the flag of skip first frame.
:return: flag of skip first frame.
:rtype: bool
"""
return self.apngasm.is_skip_first()
def frame_count(self) -> int:
"""
Returns the number of frames.
:return: number of frames.
:rtype: int
"""
return self.apngasm.frame_count()
def reset(self) -> int:
"""
Destroy all frames in memory/dispose of the frame vector.
Leaves the apngasm object in a clean state.
Returns number of frames disposed of.
:return: number of frames disposed of.
:rtype: int
"""
return self.apngasm.reset()
def version(self) -> str:
"""
Returns the version of APNGAsm.
:return: version of APNGAsm.
:rtype: str
"""
return self.apngasm.version()