-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathIconolatry.py
1449 lines (1263 loc) · 83.7 KB
/
Iconolatry.py
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from struct import unpack_from, pack, calcsize
from PIL import Image, ImageCms
from tempfile import mkstemp
from os.path import isfile, splitext, abspath, isdir, join, basename
from os import listdir
from io import BytesIO
import sys
import argparse
from functools import partial
from itertools import chain
__version__ = "2.0"
__license__ = "MIT License"
__author__ = u"Matteo ℱan <[email protected]>"
__copyright__ = "© Copyright 2018-2021"
__url__ = "https://github.com/SystemRage/Iconolatry"
__summary__ = "Advanced Icon Converter"
## _________
##| Generic |-----------------------------------------------------------------------------------------------------------------------------------------------
##|_________|
##
is_cli = False
working_path = abspath('.')
def calc_rowsize(bits, width):
""" Computes number of bytes per row in a image (stride). """
## The size of each row is rounded up to the nearest multiple of 4 bytes.
return int(((bits * width + 31) // 32)) * 4
def calc_masksize(width):
""" Computes number of bytes for AND mask. """
return int((width + 32 - width % 32 if (width % 32) > 0 else width) / 8)
def print_err(msg, view = True, toexit = True):
""" Handles stderr. """
if view:
sys.stderr.write(msg + '\n')
sys.stderr.flush()
if toexit:
sys.exit(1)
def print_std(msg, view = False):
""" Handles stdout. """
if view:
sys.stdout.write(msg + '\n')
sys.stdout.flush()
class EncodeErr(Exception):
""" Custom encode exception. """
def __init__(self, **kwargs):
self.code, self.msg = kwargs['code'], kwargs['msg']
## ________
##| Parser |------------------------------------------------------------------------------------------------------------------------------------------------
##|________|
##
def tupledict(value):
from ast import literal_eval
try:
value = literal_eval(value)
except:
# get errors after.
pass
return value
class ExtendAction(argparse.Action):
# https://stackoverflow.com/questions/41152799/argparse-flatten-the-result-of-action-append
def __call__(self, parser, namespace, values, option_string = None):
items = getattr(namespace, self.dest) or []
items.extend(values)
setattr(namespace, self.dest, items)
def iconolatry_parser():
""" CLI parser. """
options = {}
icon_parser = argparse.ArgumentParser(description = __summary__, epilog = 'version: ' + __version__)
icon_subparsers = icon_parser.add_subparsers(dest = 'mode', help = "Select if you want to read or to write an `.ico` / `.cur`.")
# Decode parser.
dec_parser = icon_subparsers.add_parser('decode', add_help = False, allow_abbrev = False)
dec_parser.register('action', 'extend', ExtendAction)
dec_required = dec_parser.add_argument_group('required arguments')
dec_required.add_argument('-i', '--icocurs-paths', required = True, nargs = "+", action = "extend", default = [], type = str,
dest = "paths_icocurs",
help = "Path(s) of `.ico` / `.cur` file(s) or folder(s) to be decoded.")
dec_optional = dec_parser.add_argument_group('optional arguments')
dec_optional.add_argument('-h', '--help', action = "help", default = argparse.SUPPRESS,
help = "show this help message and exit")
dec_optional.add_argument('-o', '--image-paths', nargs = "+", action = "extend", default = [], type = str,
dest = "paths_image",
help = "Path(s) of `.ico` / `.cur` image(s) decoded.")
dec_optional.add_argument('-n', '--image-names', nargs = "+", action = "extend", default = [], type = str,
dest = "names_image",
help = "Name(s) of `.ico` / `.cur` image(s) decoded.")
dec_optional.add_argument('-f', '--image-formats', nargs = "+", action = "extend", default = [], type = str,
dest = "formats_image",
help = "Format(s) of `.ico` / `.cur` image(s) decoded.")
dec_optional.add_argument('-u', '--rebuild', action = 'store_true', default = False,
dest = "rebuild",
help = "Enable recompute AND mask.")
# Encode parser.
enc_parser = icon_subparsers.add_parser('encode', add_help = False, allow_abbrev = False)
enc_parser.register('action', 'extend', ExtendAction)
enc_required = enc_parser.add_argument_group('required arguments')
enc_required.add_argument('-i', '--images-paths', required = True, nargs = "+", action = "append", default = [], type = str,
dest = "paths_images",
help = "Path(s) of image file(s) or folder(s) to be encoded.")
enc_optional = enc_parser.add_argument_group('optional arguments')
enc_optional.add_argument('-h', '--help', action = "help", default = argparse.SUPPRESS,
help = "show this help message and exit")
enc_optional.add_argument('-o', '--icocur-paths', nargs = "+", action = "extend", default = [], type = str,
dest = "paths_icocur",
help = "Path(s) of `.ico` / `.cur`(s) encoded.")
enc_optional.add_argument('-n', '--icocur-names', nargs = "+", action = "extend", default = [], type = str,
dest = "names_icocur",
help = "Name(s) of `.ico` / `.cur`(s) encoded.")
enc_optional.add_argument('-f', '--icocur-formats', nargs = "+", action = "extend", default = [], type = tupledict,
dest = "formats_icocur",
help = "Format(s) of `.ico` / `.cur`(s) encoded.")
enc_optional.add_argument('-r', '--resize', action = "store", default = 'up256_prop', type = tupledict,
dest = "type_resize",
help = "Resize method (values) to apply during encoding.")
enc_optional.add_argument('-c', '--force', action = "store", default = 'raw', type = str,
dest = "force_to",
help = "Bit depth conversion method to apply during encoding.")
enc_optional.add_argument('-p', '--custom-palettes', action = "store", default = {}, type = tupledict,
dest = "custom_palettes",
help = "Palettes to apply during encoding.")
try:
options.update(vars(icon_parser.parse_args()))
except Exception as e:
raise e
return options
## _____________________
##| Parameters Checker |-----------------------------------------------------------------------------------------------------------------------------------
##|_____________________|
##
class Check(object):
def __init__(self, list_in, list_out):
self.list_in, self.list_out = list_in, list_out
def setup(self):
""" Checks output length list. """
if not isinstance(self.list_out, list):
print_err("Input error: %s not a list." %self.msg)
if len(self.list_in) > len(self.list_out):
# used default for missing fields.
self.list_out.extend([self.default] * (len(self.list_in) - len(self.list_out)))
elif len(self.list_in) < len(self.list_out):
print_err("Input error: too much %s." %self.msg)
def paths(self, msg):
""" Checks output paths list. """
self.msg = msg + " directory path/s"
self.default = working_path
self.setup()
for indx, path in enumerate(self.list_out):
if not isinstance(path, str):
print_err("Input error: %s directory path '%s' not a string." %(msg, path))
else:
if path is "":
# used default for specified empty field.
self.list_out[indx] = self.default
elif not isdir(path):
print_err("Input error: %s directory path '%s' not found." %(msg, path))
def names(self, msg):
""" Checks output names list. """
self.msg = msg + " name/s"
self.default = ""
self.setup()
for indx, (path, name) in enumerate(zip(self.list_in, self.list_out)):
if not isinstance(name, str):
print_err("Input error: %s name '%s' not a string." %(msg, name))
else:
if name is "":
try:
if isinstance(path, list) and len(path) == 1:
path = path[0]
# single image --> get image name.
# directory images --> put "".
self.list_out[indx] = (splitext(basename(path))[0] if isfile(path) else self.default)
except:
# get errors after.
pass
def formats_checker(self, msg):
""" Formats checking function. """
Image.init()
for indx, frmt in enumerate(self.list_out):
if not isinstance(frmt, str):
print_err("Input error: %s format '%s' not a string." %(msg, frmt))
else:
if frmt is "":
self.list_out[indx] = self.default
else:
if (self.default == ".png" and frmt[1:].upper() not in Image.SAVE.keys()) or \
(self.default == ".ico" and frmt not in [".ico", ".cur"]):
print_err("Input error: %s format '%s' not recognized." %(msg, frmt))
def formats(self, msg, default, check = True):
""" Checks output formats list. """
self.msg = msg + " format/s"
self.default = default
self.setup()
if check:
self.formats_checker(msg)
## _______________________
##| Read `.ico` / `.cur` |----------------------------------------------------------------------------------------------------------------------------------
##|_______________________|
##
class Decode(object):
def __init__(self, paths_icocurs, paths_image = [], names_image = [], formats_image = [],
rebuild = False, force_to = 'original'):
"""
`paths_icocurs` : a list : can contain one/more icon/cursor(s) path(s)
and/or one/more folder icon/cursor(s) path(s) to convert.
`paths_image` : a list : contains output path(s) for every resulting conversion.
If `paths_image` isn't defined, working directory is used.
`names_image` : a list : contains output name(s) for every resulting conversion.
`formats_image` : a list : contains format(s) for every resulting conversion (all saving PIL formats).
`rebuild` : a bool : if 'True', recompute mask from the alpha channel data.
`force_to` : a string : if 'original', original bit depth is kept. (TODO)
"""
self.paths_icocurs = paths_icocurs
self.paths_image = paths_image
self.formats_image = formats_image
self.names_image = names_image
self.rebuild = rebuild
self.force_to = force_to
self.is_cli = is_cli
self.want_save = (False if all(x == [] for x in [self.paths_image, self.names_image, self.formats_image]) else True)
self.build()
def is_png(self, dataimage):
""" Determines whether a sequence of bytes is a PNG. """
return dataimage.startswith(b'\x89PNG\r\n\x1a\n')
def is_gray(self):
""" Determines whether an image is grayscale (from palette). """
paletteblocks = [self.parameters['palette'][i : i + 3] for i in range(0, self.parameters['size_pal'], 4)]
if all(elem == block[0] for block in paletteblocks for elem in block):
return True
else:
return False
def check_output(self):
""" Verifies if output paths, names, formats are ok. """
## Check rebuild option.
if not isinstance(self.rebuild, bool):
print_err("Input error: option 'rebuild' not a boolean.")
## Checks paths.
Check(self.paths_icocurs, self.paths_image).paths("image")
## Check names.
Check(self.paths_icocurs, self.names_image).names("image")
## Check formats.
Check(self.paths_icocurs, self.formats_image).formats("image", ".png")
def build(self):
""" Verifies if input paths are ok and starts conversion job. """
self.print_std = partial(print_std, view = self.is_cli)
self.print_err = partial(print_err, view = self.is_cli)
## Checks paths `.ico` / `.cur` files (Input).
if not self.paths_icocurs:
print_err("Input error: `.ico` / `.cur` file path/s missing.")
if isinstance(self.paths_icocurs, list):
self.check_output()
self.remind = {}
self.all_icocur_readed = {}
for self.index, self.path_icocur in enumerate(self.paths_icocurs):
if isinstance(self.path_icocur, str):
if isfile(self.path_icocur):
self.work()
else:
if isdir(self.path_icocur):
temp = self.path_icocur
for file in sorted(listdir(self.path_icocur)):
self.path_icocur = join(self.path_icocur, file)
self.work()
self.path_icocur = temp
else:
self.all_icocur_readed.update({self.path_icocur : "Input error: file/directory not found."})
elif isinstance(self.path_icocur, bytes):
self.data_icocur = self.path_icocur
self.path_icocur = "stream_%s" %self.index
self.work(is_byte = True)
else:
self.all_icocur_readed.update({self.path_icocur : "Input error: neither a file/directory nor bytes."})
else:
print_err("Input error: `.ico` / `.cur` file path/s not a list.")
def extract(self, dataimage, offset):
""" Gets bitmap parameters. """
# Should be:
# biSize is the size of the header
# biHeight doubled respect bHeight
# biPlanes = 1
# biCompression = 0 (if BI_RGB)
# biSizeImage = size of the XOR mask + AND mask (can be also 0)
# biXPelsPerMeter = 0 (if not used)
# biYPelsPerMeter = 0 (if not used)
# biClrUsed = 0 (if not used)
# biClrImportant = 0 (if not used)
## Get BITMAPINFO header data.
(biSize, biWidth, biHeight, biPlanes, biBitCount,
biCompression, biSizeImage, biXPelsPerMeter, biYPelsPerMeter, biClrUsed, biClrImportant) = unpack_from('<3L2H6L', dataimage[0 : 40])
biHeight = int(biHeight / 2.)
## Get palette, xor & and mask.
xorsize = calc_rowsize(biBitCount, biWidth) * biHeight
andsize = calc_masksize(biWidth) * biHeight
palettesize = offset - (biSize + xorsize + andsize)
if palettesize < 0:
palettesize = 0
palette = dataimage[biSize : biSize + palettesize]
xordata = dataimage[biSize + palettesize : biSize + palettesize + xorsize]
anddata = dataimage[biSize + palettesize + xorsize : len(dataimage)]
self.parameters = {"head" : biSize,
"width" : biWidth,
"height" : biHeight,
"planes" : biPlanes,
"bpp" : biBitCount,
"compress" : biCompression,
"size_img" : biSizeImage,
"colors" : biClrUsed,
"size_pal" : palettesize,
"num_pal" : 0,
"palette" : palette,
"size_xor" : xorsize,
"xor" : xordata,
"size_and" : andsize,
"and" : anddata
}
def load(self):
""" Gets image from bytes. """
modes = {32 : ("RGBA", "BGRA"),
24 : ("RGB", "BGR"),
16 : ("RGB", "BGR"),
8 : ("P", "P"),
4 : ("P", "P;4"),
2 : ("P", "P;2"),
1 : ("P", "P;1")}
if self.is_gray():
modes.update({8 : ("L", "L"),
4 : ("L", "L;4"),
2 : ("L", "L;2"),
1 : ("1", "1")})
pad_msk = calc_masksize(self.parameters['width'])
if self.parameters['bpp'] == 16:
# PIL I;16 converted to RGB555 format.
pad_ima = calc_rowsize(24, self.parameters['width'])
dataimage = []
for i in range(0, len(self.parameters['xor']), 2):
data = int.from_bytes(self.parameters['xor'][i : i + 2], byteorder = 'little')
a = (data & 0x8000) >> 15
b = (data & 0x7C00) >> 10
g = (data & 0x3E0) >> 5
r = (data & 0x1F)
r = (r << 3) | (r >> 2)
g = (g << 3) | (g >> 2)
b = (b << 3) | (b >> 2)
value = r << 16 | g << 8 | b
dataimage.append((value).to_bytes(3, byteorder = 'little'))
dataimage = b"".join(dataimage)
image = Image.frombytes(modes[self.parameters['bpp']][0], (self.parameters['width'], self.parameters['height']),
dataimage, 'raw', modes[self.parameters['bpp']][1], pad_ima, -1)
else:
pad_ima = calc_rowsize(self.parameters['bpp'], self.parameters['width'])
image = Image.frombytes(modes[self.parameters['bpp']][0], (self.parameters['width'], self.parameters['height']),
self.parameters['xor'], 'raw', modes[self.parameters['bpp']][1], pad_ima, -1)
if self.parameters['bpp'] == 32:
mask = Image.frombuffer("L", (self.parameters['width'], self.parameters['height']),
self.parameters['xor'][3::4], 'raw', 'L', 0, -1)
else:
mask = Image.frombuffer("1", (self.parameters['width'], self.parameters['height']),
self.parameters['and'], 'raw', '1;I', pad_msk, -1)
if self.parameters['palette'] and self.parameters['bpp'] <= 8:
image = image.convert('P')
palette_int = [self.parameters['palette'][i : i + 3] for i in range(0, self.parameters['size_pal'], 4)]
rsv = [self.parameters['palette'][i + 3 : i + 4] for i in range(0, self.parameters['size_pal'], 4)]
if (self.parameters['size_pal'] % 3 == 0) and (self.parameters['size_pal'] % 4 == 0):
if len(set(rsv)) <= 1:
# palette RGBA.
palette_int = [pal[i] for pal in palette_int for i in reversed(range(3))]
self.parameters['num_pal'] = self.parameters['size_pal'] // 4
else:
# palette RGB.
palette_int = [pal for pal in self.parameters['palette'][::-1]]
self.parameters['num_pal'] = self.parameters['size_pal'] // 3
else:
if self.parameters['size_pal'] % 3 == 0:
# palette RGB.
palette_int = [pal for pal in self.parameters['palette'][::-1]]
self.parameters['num_pal'] = self.parameters['size_pal'] // 3
elif self.parameters['size_pal'] % 4 == 0:
# palette RGBA.
palette_int = [pal[i] for pal in palette_int for i in reversed(range(3))]
self.parameters['num_pal'] = self.parameters['size_pal'] // 4
## PIL is wonky with next RGBA conversion,
## if the palette isn't complete (768 values) for bilevel.
if self.parameters['bpp'] == 1:
pal = list(image.palette.getdata()[1])
pal[:3], pal[-3:] = palette_int[:3], palette_int[-3:]
palette_int = pal
# Assign palette.
image.putpalette(palette_int)
image = image.convert('RGBA')
image.putalpha(mask)
return image
def from_icocur(self):
""" Reads an `.ico` / `.cur` file and checks whether it's acceptable. """
def add_warning(dict_icocur, num, msg):
if 'warning' in dict_icocur['image_%s' %num]:
dict_icocur['image_%s' %num]['warning'].append(msg)
else:
dict_icocur['image_%s' %num].update({'warning' : [msg]})
icocur_readed = {}
typ = {1 : 'ICO',
2 : 'CUR'}
datasize = len(self.data_icocur)
identf, count = unpack_from('<2H', self.data_icocur[2 : 6])
## Control if it's a `.ico` / `.cur` type and extract values.
if identf not in [1, 2]:
self.all_icocur_readed.update({self.path_icocur : "Icon/Cursor error: invalid `.ico` / `.cur`."})
return
else:
if identf == 1 and self.path_icocur.endswith('.cur'):
msg = "Not a real `.cur` ! It's an icon with extension `.cur`."
icocur_readed.update({'warning' : [msg]})
elif identf == 2 and self.path_icocur.endswith('.ico'):
msg = "Not a real `.ico` ! It's a cursor with extension `.ico`."
icocur_readed.update({'warning' : [msg]})
## Note: always one frame for `.cur`.
icondirentries = [unpack_from('<4B2H2L', self.data_icocur[6 + 16 * i : 22 + 16 * i]) for i in range(count)]
for cnt in range(count):
# Should be:
# wPlanes = 0 (if not used)
# wBitCount = 0 (if not used)
# dwBytesInRes is the total number of bytes in the image data, including palette data
# dwImageOffset is offset from the beginning of the file to the image data
icocur_readed.update({'image_%s' %cnt: {}})
bWidth, bHeight, bColorCount, bReserved, \
wPlanes_or_wXHotSpot, wBitCount_or_wYHotSpot, dWBytesInRes, dWImageOffset = icondirentries[cnt]
bWidth = bWidth or 256
bHeight = bHeight or 256
if cnt == 0:
totalsize = dWImageOffset + dWBytesInRes
else:
totalsize += dWBytesInRes
icocurdata_with_header = self.data_icocur[dWImageOffset : dWImageOffset + dWBytesInRes]
png_flag = self.is_png(icocurdata_with_header)
if not png_flag:
if bWidth >= 256 or bHeight >= 256:
add_warning(icocur_readed, cnt, "Is a large uncompressed `bmp` ! Should be `png` format.")
## Get bmp parameters.
self.extract(icocurdata_with_header, dWBytesInRes)
## Get mask and check it.
self.parameters, chk = Mask().rebuild_AND_mask(icocurdata_with_header, self.parameters, self.rebuild)
if not chk:
add_warning(icocur_readed, cnt, "Bad mask found ! Will display incorrectly in some places (Windows).")
## Other checks.
try:
assert bWidth == self.parameters['width'], ('width')
assert bHeight == self.parameters['height'], ('height')
if identf == 1:
assert (wPlanes_or_wXHotSpot in [0, 1]) and (self.parameters['planes'] == 1), ('planes')
assert (wBitCount_or_wYHotSpot == 0) or (wBitCount_or_wYHotSpot == self.parameters['bpp']), ('bits')
assert self.parameters['compress'] == 0, ('compression')
if (self.parameters['size_img'] != 0) and \
(self.parameters['size_img'] != self.parameters['size_xor'] + self.parameters['size_and']):
# it seems legal to put a wrong 'size_img' !
add_warning(icocur_readed, cnt, "Size image malformed value !")
assert (bColorCount == self.parameters['colors']) or \
(bColorCount == 0 and self.parameters['colors'] == 1 << wBitCount_or_wYHotSpot) or \
(bColorCount == 0 and self.parameters['colors'] == 1 << self.parameters['bpp']) or \
(bColorCount == 1 << wBitCount_or_wYHotSpot and self.parameters['colors'] == 0) or \
(bColorCount == 1 << self.parameters['bpp'] and self.parameters['colors'] == 0), ('color count')
except AssertionError as e:
icocur_readed.update({'image_%s' %cnt : "Image error: malformed %s." %e.args[0]})
continue
try:
image = self.load()
icocur_readed['image_%s' %cnt].update({'im_obj' : image,
'depth' : self.parameters['bpp']})
if self.parameters['num_pal'] > 0:
icocur_readed['image_%s' %cnt].update({'num_pal' : self.parameters['num_pal']})
except:
icocur_readed.update({'image_%s' %cnt : "Image error: image not supported."})
continue
elif png_flag:
icocurdata = BytesIO(icocurdata_with_header)
image = Image.open(icocurdata)
if image:
w, h = image.size
icocurdata = icocurdata.getvalue()
bitdepth, colortype = unpack_from('<2B', icocurdata[24 : 26])
bpp = len(image.getbands()) * bitdepth
## Other checks.
try:
assert bWidth == w , ('width')
assert bHeight == h , ('height')
if identf == 1:
assert wPlanes_or_wXHotSpot in [0, 1], ('planes')
assert (wBitCount_or_wYHotSpot == 0) or (wBitCount_or_wYHotSpot == bpp), ('bits')
assert (bColorCount == 0) or (bColorCount == 1 << wBitCount_or_wYHotSpot), ('color count')
elif identf == 2:
assert bColorCount == 0, ('color count')
except AssertionError as e:
icocur_readed.update({'image_%s' %cnt : "Image error: malformed %s." %e.args[0]})
continue
icocur_readed['image_%s' %cnt].update({'info' : {'format' : "`png` compressed"}})
if image.info:
icocur_readed['image_%s' %cnt]['info'].update(image.info)
icocur_readed['image_%s' %cnt].update({'im_obj' : image,
'depth' : bpp})
if image.palette:
modepal, palette = image.palette.getdata()
if modepal in ['RGB', 'RGB;L']:
palettenum = int(len(palette) / 3)
elif modepal in ['RGBA', 'RGBA;L']:
palettenum = int(len(palette) / 4)
icocur_readed['image_%s' %cnt].update({'num_pal' : palettenum})
else:
icocur_readed.update({'image_%s' %cnt : "Image error: neither `bmp` nor `png`."})
continue
if identf == 2:
icocur_readed['image_%s' %cnt].update({'hotspot_x' : wPlanes_or_wXHotSpot,
'hotspot_y' : wBitCount_or_wYHotSpot})
if datasize != totalsize:
self.all_icocur_readed.update({self.path_icocur : "Icon/Cursor error: invalid %s, unexpected EOF." %typ[identf]})
return
return icocur_readed
def printsave(self):
""" Saves conversion file and print results. """
current = self.paths_icocurs[self.index]
result = self.all_icocur_readed[self.path_icocur]
if isinstance(result, dict):
self.print_std('\n' + '#' * 80 + '\n')
if isinstance(current, bytes):
self.print_std('bytes = %s\n' %self.path_icocur)
else:
if isdir(current):
self.print_std('folder = %s\n' %current)
self.print_std('file = %s\n' %self.path_icocur)
for indx, key in enumerate(result):
self.print_std('** ' + key + ' **')
subresult = result[key]
if isinstance(subresult, dict):
if 'warning' in subresult:
# print image warnings.
for warn in subresult['warning']:
self.print_err(warn, toexit = False)
if 'info' in subresult:
# print image info png.
inf = ', '.join('{} = {}'.format(k, v) for k, v in subresult['info'].items())
self.print_std('info --> %s' %inf)
self.print_std('(width, height) = %s' %str(subresult['im_obj'].size))
self.print_std('depth = %s' %subresult['depth'])
if 'num_pal' in subresult:
# print image palette size.
self.print_std('palette length = %s' %subresult['num_pal'])
if 'hotspot_x' in subresult:
# print `.cur` hotspots.
self.print_std('(hotspot_x, hotspot_y) = %s' %str((subresult['hotspot_x'], subresult['hotspot_y'])))
# save.
if self.want_save or self.is_cli:
# define current path, name and format.
path, name, frmt = self.paths_image[self.index], \
self.names_image[self.index], \
self.formats_image[self.index]
if name == "":
name = splitext(basename(self.path_icocur))[0]
# define current index.
couple = (path, name)
current_indx = (indx + self.remind[couple] + 1 if couple in self.remind.keys() else indx)
# define current name with index.
current_name = (name + '_' + str(current_indx) if len(result) > 1 or couple in self.remind.keys() else name)
save_path = join(path, current_name + frmt)
subresult['im_obj'].save(save_path, format = frmt[1:].upper())
subresult.update({'saved' : save_path})
self.print_std('saved as = %s' %save_path)
else:
if isinstance(subresult, list):
for warn in subresult:
self.print_err(warn, toexit = False)
else:
self.print_err(subresult, toexit = False)
# remind last index bound to a specific path and name.
if isinstance(subresult, dict):
self.remind.update({couple : current_indx})
else:
self.print_err(result, toexit = False)
def work(self, is_byte = False):
""" Executes conversion job."""
if not is_byte:
if self.path_icocur.lower().endswith('.ico') or self.path_icocur.lower().endswith('.cur'):
with open(self.path_icocur, 'rb') as file:
self.data_icocur = file.read()
else:
print_err("Input error: not an `.ico` / `.cur` file.")
ico_r = self.from_icocur()
if ico_r:
self.all_icocur_readed.update({self.path_icocur : ico_r})
## Show / save results.
self.printsave()
## __________________
##| Mask Operations |--------------------------------------------------------------------------------------------------------------------------------------
##|__________________|
##
class Mask(object):
""" edited / adapted parts of:
https://chromium.googlesource.com/chromium/src/+/master/tools/resources/ico_tools.py
"""
def compute_AND_mask(self, width, height, xordata):
""" Computes AND mask from 32-bit BGRA image data. """
andbytes = []
for y in range(height):
bitcounter, currentbyte = (0 for _ in range(2))
for x in range(width):
alpha = xordata[(y * width + x) * 4 + 3]
currentbyte <<= 1
if alpha == 0:
currentbyte |= 1
bitcounter += 1
if bitcounter == 8:
andbytes.append(currentbyte)
bitcounter, currentbyte = (0 for _ in range(2))
## Pad current byte at the end of row.
if bitcounter > 0:
currentbyte <<= (8 - bitcounter)
andbytes.append(currentbyte)
## Keep padding until multiple 4 bytes.
while len(andbytes) % 4 != 0:
andbytes.append(0)
andbytes = b"".join(pack('B', andbyte) for andbyte in andbytes)
return andbytes
def check_AND_mask(self, width, height, xordata, anddata):
""" Verifies if AND mask is good for 32-bit BGRA image data.
1- Checks if AND mask is opaque wherever alpha channel is not fully transparent.
2- Checks inverse rule, AND mask is transparent wherever alpha channel is fully transparent.
"""
xorbytes = width * 4
andbytes = calc_rowsize(1, width)
for y in range(height):
for x in range(width):
alpha = ord(bytes([xordata[y * xorbytes + x * 4 + 3]]))
mask = bool(ord(bytes([anddata[y * andbytes + x // 8]])) & (1 << (7 - (x % 8))))
if mask:
if alpha > 0:
## mask transparent, alpha partially or fully opaque. This pixel
## can show up as black on Windows due to a rendering bug.
return False
else:
if alpha == 0:
## mask opaque, alpha transparent. This pixel should be marked as
## transparent in the mask, for legacy reasons.
return False
return True
def rebuild_AND_mask(self, dataimage, parameters, rebuild = False):
""" Checks icon image AND mask for correctness, or rebuilds it.
With rebuild == False, checks whether the mask is bad.
With rebuild == True, throw the mask away and recompute it from the alpha channel data.
"""
# Note: the monochrome AND mask does not have a palette table.
check = True
if parameters['bpp'] != 32:
## No alpha channel, so the mask cannot be wrong.
return parameters, check
else:
if rebuild:
parameters['and'] = self.compute_AND_mask(parameters['width'], parameters['height'], parameters['xor'])
return parameters, check
else:
return parameters, self.check_AND_mask(parameters['width'], parameters['height'], parameters['xor'], parameters['and'])
## ________________________
##| Write `.ico` / `.cur` |---------------------------------------------------------------------------------------------------------------------------------
##|________________________|
##
class Encode(object):
def __init__(self, paths_images, paths_icocur = [], names_icocur = [], formats_icocur = [],
type_resize = 'up256_prop', force_to = 'original', custom_palettes = {}):
"""
`paths_images` : a list of lists : every list can contain one/more image(s) path(s)
and/or one/more folder image(s) path(s) to convert.
`paths_icocur` : a list : contains output path(s) for every resulting conversion.
If `paths_icocur` isn't defined, working directory is used.
`names_icocur` : a list : contains output name(s) for every resulting conversion.
If `paths_images` contains a *folder path* and corresponding `names_icocur` is defined,
a multi-`.ico` is created (note: multi-`.cur` creation is forbidden), otherwise
every image in *folder path* is converted to a single `.ico` / `.cur`.
`formats_icocur` : a list : contains format(s) for every resulting conversion (that is ".ico" or ".cur").
If ".cur", can be specified hotspot x (integer) and hotspot y (integer)
using a tuple; example: (".cur", 2, 5).
`type_resize` : a string or tuple : If used 'up256_prop' / 'up256_no_prop' dimensions greater than 256 pixels are resized
keeping / without keeping global image aspect ratio.
If used 'square', dimensions are resized to nearest square standard size.
Can be also provided a custom resize tuple (width, height).
`force_to` : a string : If 'original', original bit depth is kept. (TODO)
`custom_palettes`: a dict : The key is a tuple (mode, bitdepth), the value can be
a list of RGB tuples [(R1,G1,B1),...,(Rn,Bn,Gn)] (usual palette format) or
a list flat [V1,V2,...,Vn] (compact format for grayscale palette) or
a '.gpl' file path.
"""
self.paths_images = paths_images
self.paths_icocur = paths_icocur
self.names_icocur = names_icocur
self.formats_icocur = formats_icocur
self.type_resize = type_resize
self.force_to = force_to
self.custom_palettes = custom_palettes
self.is_cli = is_cli
self.build()
def add_name2path(self, name, frmt, indx):
""" Adds `.ico` / `.cur` name to output path. """
couple = (self.path_icocur, name)
current_indx = (self.remind[couple] + 1 if couple in self.remind.keys() else indx)
current_name = (name + '_' + str(current_indx) if couple in self.remind.keys() else name)
self.remind.update({(self.path_icocur, name) : current_indx})
self.path_icocur = join(self.path_icocur, current_name + frmt)
def add_errors(self, msg):
""" Assigns / prints process errors."""
self.all_icocur_written.update({self.path_icocur : msg})
self.print_err(msg)
def check_output(self):
""" Verifies if output paths, names, formats are ok. """
## Check other options.
if not isinstance(self.type_resize, (tuple, str)):
print_err("Input error: option `type_resize` not a tuple or a string.")
else:
if isinstance(self.type_resize, tuple) and not (len(self.type_resize) == 2 \
and all(isinstance(tyr, int) for tyr in [self.type_resize[0], self.type_resize[1]]) \
and self.type_resize[0] <= 256 and self.type_resize[1] <= 256):
print_err("Input error: option `type_resize` tuple not proper defined.")
elif isinstance(self.type_resize, str) and (self.type_resize not in ['up256_prop', 'up256_no_prop', 'square']):
print_err("Input error: option `type_resize` unknown '%s' method." %self.type_resize)
if self.force_to not in ['original']:
print_err("Input error: option `force_to` not proper defined.")
## Check paths.
msg = "icon / cursor"
Check(self.paths_images, self.paths_icocur).paths(msg)
## Check names.
Check(self.paths_images, self.names_icocur).names(msg)
## Check formats.
# 1 - check length list.
frmtchk = Check(self.paths_images, self.formats_icocur)
frmtchk.formats(msg, ".ico", check = False)
# 2 - check hotspots (for `.cur`).
self.hotspots = []
for i, frmt in enumerate(self.formats_icocur):
if isinstance(frmt, tuple):
if frmt[0] == '.ico':
print_err("Input error: hotspot specification invalid for `.ico` conversion.")
if all(not isinstance(hot, int) for hot in frmt[1::]) or (len(frmt[1::]) != 2):
print_err("Input error: hotspot specification not proper defined.")
self.formats_icocur[i] = frmt[0]
self.hotspots.append(frmt[1::])
else:
if frmt == '.ico':
self.hotspots.append("")
elif frmt == '.cur':
self.hotspots.append((0, 0))
# 3 - check extensions.
frmtchk.formats_checker(msg)
def build(self):
""" Verifies if input paths are ok and starts conversion job. """
self.print_std = partial(print_std, view = self.is_cli)
self.print_err = partial(print_err, view = self.is_cli)
## Check paths images.
if self.paths_images and isinstance(self.paths_images, list):
self.check_output()
self.remind = {}
self.all_icocur_written = {}
groups = zip(self.paths_images, self.paths_icocur, self.names_icocur, self.formats_icocur, self.hotspots)
for indx, (path_image, self.path_icocur, name, frmt, hotspot) in enumerate(groups):
self.print_std('#' * 80)
no_err, paths = True, []
if isinstance(path_image, list):
if not path_image:
no_err = False
message = "Input error: image file/directory path/s missing."
else:
for imapath in path_image:
if not isinstance(imapath, str):
no_err = False
message = "Input error: image file/directory path '%s' not a string." %imapath
else:
if isfile(imapath):
paths.append(imapath)
else:
if isdir(imapath):
paths.extend([join(imapath, file) for file in listdir(imapath)])
else:
no_err = False
message = "Input error: file/directory '%s' not found." %imapath
if len(paths) > 1:
if frmt == '.cur':
if name != "":
no_err = False
message = "Input error: can't create multi-size '.cur'."
else:
# eventually remove duplicate jobs.
paths = list(set(paths))
elif frmt == '.ico':
if name == "":
name = 'multi'
else:
no_err = False
message = "Input error: image file/directory path/s not a list of lists."
## Do job.
if name != "":
self.add_name2path(name, frmt, indx)
if not no_err:
if name == "":
self.add_name2path('noname', frmt, indx)
self.add_errors(message)
else:
self.work(paths, name, frmt, hotspot)
else:
print_err("Input error: image file/directory path/s not a list of lists.")
def convert_8bit_to_4bit(self, bits_8):
""" Converts 8-bit image data to 4-bit. """
bits_4 = []
for i in range(0, len(bits_8), 2):
high = bits_8[i] & 0b11110000
low = bits_8[i + 1] & 0b00001111
bits_4 += [high | low]
return bytes(bits_4)
def convert_8bit_to_2bit(self, bits_8):
""" Converts 8-bit image data to 2-bit. """
bits_2 = []
for i in range(0, len(bits_8), 4):
hh = bits_8[i] & 0b11000000
hl = bits_8[i + 1] & 0b00110000
lh = bits_8[i + 2] & 0b00001100
ll = bits_8[i + 3] & 0b00000011
bits_2 += [hh | hl | lh | ll]
return bytes(bits_2)
def convert_16bit_to_8bit(self, bits_16):
""" Converts 16-bit image data to 8-bit """
pass
def get_bgra(self, image, pad):
""" Gets image data for RGBA. """
try:
dataimage = image.tobytes('raw', 'BGRA', pad, -1)
except SystemError:
# workaround for earlier versions.
r, g, b, a = image.split()
image = Image.merge('RGBA', (b, g, r, a))
dataimage = image.tobytes('raw', 'BGRA', pad, -1)
return dataimage
def extract(self, path):
""" Gets parameters input image. """
## Open image in-memory as '.png'.
_, ext = splitext(path)
try:
image = Image.open(path, 'r')
except:
raise EncodeErr(code = 1, msg = "Image error: format '%s' not recognized or corrupted." %ext)
imagebyte = BytesIO()
try:
image.save(imagebyte, format = 'PNG')
except:
raise EncodeErr(code = 1, msg = "Image error: format '%s' not recognized or corrupted." %ext)
dataimage = imagebyte.getvalue()
image = Image.open(imagebyte)
self.parameters['bWidth'], self.parameters['bHeight'] = image.size
self.mode = image.mode
## PNG color type represent sums of this values: 1 (palette used), 2 (color used) and 4 (alpha channel used)
## Color Option - Channels - Bits per channel - Bits per pixel - Color type - Interpretation
## indexed 1 1,2,4,8 1,2,4,8 3 each pixel is a palette index
## grayscale 1 1,2,4,8,16 1,2,4,8,16 0 each pixel is a grayscale sample
## grayscale+alpha 2 8,16 16,32 4 each pixel is a grayscale sample followed by an alpha sample
## truecolor 3 8,16 24,48 2 each pixel is an R,G,B triple
## truecolor+alpha 4 8,16 32,64 6 each pixel is an R,G,B triple followed by an alpha sample
with open(path, 'rb') as file:
data = file.read(30)
bitdepth, coltyp = unpack_from('<2B', data[24 : 26])
self.parameters['wBitCount'] = len(image.getbands()) * bitdepth
if coltyp == 4 and self.mode == 'RGBA':
# fix this PIL mode.
self.mode, self.parameters['wBitCount'] = ('LA', int(self.parameters['wBitCount'] / 2))
dict_colortype = {0 : (['1', 'I', 'L'], 'grayscale'),
2 : (['RGB'], 'truecolor'),
3 : (['P'], 'indexed'),
4 : (['LA'], 'grayscale+alpha'),