-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpdfimage.py
executable file
·2093 lines (1650 loc) · 85.2 KB
/
pdfimage.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
# Write this man about the bug in PIL Image.paste()!
# https://sudonull.com/post/129265-Alpha_composite-optimization-history-in-Pillow-20
# https://habr.com/ru/post/98743/
# https://github.com/homm/
# https://twitter.com/wouldntfix
from pdfrw import PdfReader, PdfWriter, PdfObject, PdfName, PdfArray, PdfDict, IndirectPdfDict
from pdfrw import py23_diffs # Ugly, but necessary: https://github.com/pmaupin/pdfrw/issues/161
from pdfrwx.common import err, msg, warn, eprint, get_key, get_any_key, getExecPath
from pdfrwx.pdffilter import PdfFilter
from pdfrwx.pdfobjects import PdfObjects
from pdfrwx.pdffunctionparser import PdfFunction
from simage import SImage
from attrdict.attrdict import AttrDict
from typing import Union
import argparse, struct, zlib, base64, sys, re, os, subprocess, tempfile
from io import BytesIO
import numpy as np
import shutil
from PIL import Image, TiffImagePlugin, ImageChops, ImageCms
Image.MAX_IMAGE_PIXELS = None
from glymur import Jp2k
from pprint import pprint
CMYK_DEFAULT_ICC_PROFILE = open(os.path.join(getExecPath(),'color_profiles/USWebCoatedSWOP.icc'), 'rb').read()
# ============================================================== timeit
from time import time
tStart = time()
def timeit(s): print(f'TIME: {s}: {time()-tStart:0.3f} sec')
# ============================================================== class OS
class OS:
def execute(cmd:list[str]):
'''
Execute command + arguments given a list: cmd[0] is the executable's name,
cmd[1:] are the command's arguments. On Windows, the .exe extension should be omitted.
'''
exe = '.exe' if sys.platform == 'win32' else ''
result = subprocess.run([cmd[0] + exe] + cmd[1:], capture_output=True)
if result.returncode != 0: sys.exit(f'execute() error: {result.stderr.decode()}')
return result.stdout.decode()
# ========================================================================== class PdfColorSpace
# Typedef
CS_TYPE = Union[PdfName, PdfArray]
class PdfColorSpace:
# A mapping from color space name to components per pixel; None means that cpp varies
spaces = {
'/DeviceGray': 1, '/CalGray': 1, '/Indexed': 1, '/Separation': 1,
'/DeviceRGB': 3, '/CalRGB': 3, '/Lab': 3, '/DeviceCMYK': 4,
'/ICCBased': None, '/DeviceN': None, '/NChannel': None
}
# A mapping from components per pixel to PIL image modes
modes = {1:'L', 3:'RGB', 4:'CMYK'}
@staticmethod
def toStr(cs:CS_TYPE):
return cs if isinstance(cs, str) \
else [type(x) if type(x) in [PdfArray, PdfDict, bytes] else x for x in cs]
@staticmethod
def get_name(cs:CS_TYPE):
'''
Returns the name of the color space (on of the PdfColorSpace.spaces.keys())
'''
name = cs if not isinstance(cs,PdfArray) \
else '/NChannel' if cs[0] == '/DeviceN' and len(cs) == 5 and cs[4].Subtype == '/NChannel' \
else cs[0]
if name != None and name not in PdfColorSpace.spaces:
raise ValueError(f'bad color space: {cs}')
return name
@staticmethod
def get_cpp(cs:CS_TYPE):
'''
Return the number of components per pixel for a give color space.
'''
name = PdfColorSpace.get_name(cs)
return int(cs[1].N) if name == '/ICCBased' else \
len(cs[1]) if name in ['/DeviceN', '/NChannel'] else \
PdfColorSpace.spaces.get(name)
@staticmethod
def get_mode(cs:CS_TYPE, bpc:int):
'''
'''
return '1' if bpc == 1 else PdfColorSpace.modes.get(PdfColorSpace.get_cpp(cs))
@staticmethod
def get_icc_profile(cs:CS_TYPE):
'''
For calibrated /CalGray, /CalRGB, /Lab and /ICCBased color spaces, returns
the ICC color profile as a bytes object. For the /Indexed color space,
returns the ICC color profile of the 'base' color space, if present, or None.
For all other color spaces returns None.
'''
name = PdfColorSpace.get_name(cs)
if name == '/Indexed': return PdfColorSpace.get_icc_profile(cs[1])
elif name == '/ICCBased': return py23_diffs.convert_store(PdfFilter.uncompress(cs[1]).stream)
elif name in ['/CalGray','/CalRGB', '/Lab']: return PdfColorSpace.create_profile(cs)
else: None
@staticmethod
def get_palette(cs:CS_TYPE):
'''
Return a tuple (paletteColorSpace, paletteArray), where paletteArray is a numpy array of shape (-1, cpp),
cpp is the number of color components in the paletteColorSpace.
'''
if PdfColorSpace.get_name(cs) != '/Indexed': return None, None
name, base, hival, pal = cs
# pal is either a IndirectPdfDict, with palette in its stream, or a PdfString
pal = py23_diffs.convert_store(PdfFilter.uncompress(pal).stream) if isinstance(pal,PdfDict) \
else pal.to_bytes()
# Fix the tail if necessary
palette_cpp = PdfColorSpace.get_cpp(base)
size = (int(hival) + 1) * palette_cpp
while len(pal) > size and pal[-1] in b'\n\r':
pal = pal[:-1]
if len(pal) != size:
raise ValueError(f'palette size mismatch: expected {size}, got {len(pal)}')
return base, np.frombuffer(pal, 'uint8').reshape(-1, palette_cpp)
@staticmethod
def create_profile(cs:CS_TYPE):
'''
Creates an ICC profile for a given color space, when it's one of ['/CalGray', ..], ['/CalRGB', ..], ['/Lab', ..]
'''
name = PdfColorSpace.get_name(cs)
if name not in ['/CalGray','/CalRGB', '/Lab']: return None
dic = cs[1]
# Calculate the CIR xyY values of the white point
X,Y,Z = [float(v) for v in dic.WhitePoint]
x,y = X/(X+Y+Z), Y/(X+Y+Z)
try:
# LittleCMS allows to specify the white point directly when creating a Lab profile
import littlecms as lc
except:
lc = None
if lc:
ctx = lc.cmsCreateContext(None, None)
white = lc.cmsCIExyY()
white.x, white.y, white.Y = x, y, Y
if name == '/Lab':
profile = lc.cmsCreateLab2Profile(white)
if name == '/CalGray':
gamma = float(dic.Gamma) if dic.Gamma != None else 1
transferFunction = lc.cmsBuildGamma(ctx,gamma)
profile = lc.cmsCreateGrayProfile(white, transferFunction)
if name == '/CalRGB':
primaries = [float(v) for v in dic.Matrix] if dic.Matrix != None else [1,0,0,0,1,0,0,0,1]
primaries = [primaries[3*i:3*i+3] for i in range(3)]
primaries = [[X/(X+Y+Z),Y/(X+Y+Z),Y] for X,Y,Z in primaries]
gamma = [float(v) for v in dic.Gamma] if dic.Gamma != None else [1,1,1]
transferFunction = [lc.cmsBuildGamma(ctx, g) for g in gamma]
pt = lc.cmsCIExyYTRIPLE()
pt.Red = lc.cmsCIExyY(); pt.Red.x, pt.Red.y, pt.Red.Y = primaries[0]
pt.Green = lc.cmsCIExyY(); pt.Green.x, pt.Green.y, pt.Green.Y = primaries[1]
pt.Blue = lc.cmsCIExyY(); pt.Blue.x, pt.Blue.y, pt.Blue.Y = primaries[2]
profile = lc.cmsCreateRGBProfile(white, pt, transferFunction)
with tempfile.TemporaryDirectory() as tmp:
T = lambda fileName: os.path.join(tmp, fileName)
lc.cmsSaveProfileToFile(profile, T('profile.cms'))
icc_profile = open(T('profile.cms'),'rb').read()
# with BytesIO() as bs:
# lc.cmsSaveProfileToStream(profile, bs)
# icc_profile = bs.getvalue()
else:
warn('LittleCMS not installed')
warn('using ImageCMS with the (approximate) McCamy\'s formula for correlated temperature')
n = (x - 0.3320) / (0.1858 - y)
CCT = 449 * n*n*n + 3525 * n*n + 6823.3 * n + 5520.33
if name == '/Lab':
icc_profile = ImageCms.createProfile('LAB', colorTemp = CCT)
if name == '/CalRGB':
return None
if dic.BlackPoint != None: warn(f'/BlackPoint ignored: {cs}')
if dic.Range != None: warn(f'/Range ignored: {cs}')
return icc_profile
@staticmethod
def reduce(cs:CS_TYPE, array:np.ndarray, Decode:list[float] = None, bpc:int = 8, mask:PdfDict = None):
'''
Reduces the image array:
* decodes it using the specified Decode array if it's not None or otherwise
the default decode array, which is determined based on the specified colorspace and bpc;
see PDF Ref. 1.7 sec. 4.8.4, Table 4.40
* un-multiplies alpha if mask.Matte is not None;
* if the colorspace is one of `/Separation`, `/DeviceN`, `/NChannel`, reduces the colorspace
by remapping the image array to the corresponding alternate colorspace;
* encodes the image array using the default Decode array based on the target colorspace
(the original or the alternate one, depending on whether the colorspace has been reduced
in the previous step) and the value of bpc == 8.
Returns the tuple (newColorSpace, array).
'''
SPECIAL = ['/Separation', '/DeviceN', '/NChannel']
name = PdfColorSpace.get_name(cs)
h,w = array.shape[:2]
assert array.ndim in [2,3]
if bpc == 1:
warn(f'cannot apply colorspace {name} to a bitonal image; skipping')
return cs, array
msg(f'applying color space: {name}')
Matte = mask.Matte if mask else None
default_decode = PdfDecodeArray.get_default(cs, bpc)
applyDecode = bpc != 8 or Matte or Decode and ((name in SPECIAL) or (Decode != default_decode))
# Decode
if applyDecode:
Decode = Decode or default_decode
array = PdfDecodeArray.decode(array, Decode, bpc)
# Matte
if Matte:
# Get matte array
matte_array = np.array([float(x) for x in Matte])[np.newaxis, np.newaxis, :]
# Render alpha
alpha = PdfImage(obj = mask)
alpha.render()
# Resize alpha
if alpha.w() != w or alpha.h() != h:
msg(f'resizing alpha: {alpha.w()} x {alpha.h()} --> {w} x {h}')
alpha.resize(w,h)
# Get decoded alpha array
alpha_array = alpha.get_array()
alpha_decode_default = PdfDecodeArray.get_default(alpha.ColorSpace, alpha.bpc)
alpha_array = PdfDecodeArray.decode(alpha.get_array(), alpha_decode_default, alpha.bpc)
alpha_array = alpha_array[:,:,np.newaxis]
# Un-multiply alpha
msg(f'Unmultiplying alpha; Matte = {Matte}')
array = matte_array + (array - matte_array) / np.maximum(alpha_array, 0.000001)
# Remove Matte entry from the mask
mask.Matte = None
# These color spaces are function-based, so apply this function
if name in SPECIAL:
altColorSpace, colorTransformFunction = cs[2], cs[3]
array = array if array.ndim == 3 else np.dstack([array])
stack = np.moveaxis(array,-1,0)
stack = PdfFunction(colorTransformFunction).process(stack)
array = np.moveaxis(stack,0,-1)
cs = altColorSpace
# Encode with bpc == 8
if applyDecode:
array = PdfDecodeArray.encode(array, PdfDecodeArray.get_default(cs, 8))
return cs, array
# @staticmethod
# def apply_default_page_colorspace_icc_profile(page:PdfDict, cs:CS_TYPE):
# '''
# If image.inf['icc_profile'] == None, apply the ICC profile from the page's default color space
# (an entry in page.Resources.Colorspace, if present) to the image (in-place).
# '''
# if page == None or image.info.get('icc_profile'): return
# try:
# default_cs = page.Resources.ColorSpace[cs]
# except:
# pass
# @staticmethod
# def make_indexed_colorspace(palette:bytes, baseColorspace):
# '''
# Returns an /Indexed colorspace based on the image's palette and baseColorspace, or
# None if image has no palette.
# '''
# # palette = image.getpalette()
# # if palette == None: return None
# # palette = b''.join(v.to_bytes(1,'big') for v in image.getpalette())
# cpp = PdfColorSpace.get_cpp(baseColorspace)
# assert len(palette) % cpp == 0
# palette_xobj = IndirectPdfDict(Filter = PdfName.FlateDecode,
# stream = zlib.compress(palette).decode('Latin-1'))
# return PdfArray([PdfName.Indexed, baseColorspace, len(palette) // cpp, palette_xobj])
@staticmethod
def make_icc_based_colorspace(icc_profile:bytes, N:int):
'''
Returns an /ICCBased colorspace made from the icc_profile with N being the number of color components.
'''
icc_xobj = IndirectPdfDict(
N = N,
Filter = PdfName.FlateDecode,
stream = zlib.compress(icc_profile).decode('Latin-1')
)
return PdfArray([PdfName.ICCBased, icc_xobj])
# ========================================================================== class PdfDecodeArray
class PdfDecodeArray:
'''
The class facilitates processing of image.Decode arrays.
'''
@staticmethod
def get_actual(Decode:PdfArray, cs:CS_TYPE, bpc:int):
'''
Returns actual Decode array as list[float] if self.image.Decode != None, or self.get_default(colorSpace) otherwise.
'''
FLOAT = lambda array: [float(a) for a in array]
return FLOAT(Decode) if Decode != None else PdfDecodeArray.get_default(cs, bpc)
@staticmethod
def get_default(cs:CS_TYPE, bpc:int):
'''
Returns the default Decode array for a give color space; see Adobe PDF Ref. 1.7, table 4.40 (p.345)
'''
FLOAT = lambda array: [float(a) for a in array]
name = PdfColorSpace.get_name(cs)
cpp = PdfColorSpace.get_cpp(cs)
if name == '/Lab':
d = [0.0, 100.0] + (FLOAT(cs[1].Range) if cs[1].Range != None else [-100.0, 100.0] * 2)
elif name == '/ICCBased' and cs[1].Range != None:
d = FLOAT(cs[1].Range)
elif name == '/Indexed':
d = [0, (1<<bpc)-1]
elif name == '/Pattern':
d = None
else:
d = [0.0, 1.0] * cpp
return d
@staticmethod
def decode(array:np.ndarray, Decode:list[float], bpc:int):
'''
Translates a numpy array from encoded ("stream space": int, 1..2**bpc -1)
to decoded ("image space", float: mostly 0.0..1.0) representation.
The array should be (D+1) dimensional, where D is the # of dimensions of the image
and the last dimension is for the color index.
'''
assert Decode
msg(f'applying Decode: {Decode}')
INTERPOLATE = lambda x, xmin, xmax, ymin, ymax: ymin + ((x - xmin) * (ymax - ymin)) / (xmax - xmin)
iMax = float((1<<bpc) - 1)
if array.ndim == 2: array = np.dstack([array])
N = array.shape[-1] # number of colors
assert len(Decode) == 2*N
array = np.clip(array, 0, iMax).astype(float)
for i in range(N):
array[...,i] = INTERPOLATE(array[...,i], 0.0, iMax, Decode[2*i], Decode[2*i + 1])
return array if N > 1 else array[...,0]
@staticmethod
def encode(array:np.ndarray, Decode:list[float]):
'''
Translates a numpy array from decoded ("image space", float: mostly 0.0..1.0)
to encoded ("stream space", uint8: 0..255) representation.
'''
msg(f'applying Encode: {Decode}')
INTERPOLATE = lambda x, xmin, xmax, ymin, ymax: ymin + ((x - xmin) * (ymax - ymin)) / (xmax - xmin)
if array.ndim == 2: array = np.dstack([array])
N = array.shape[-1] # number of colors
assert len(Decode) == 2*N
for i in range(N):
array[...,i] = INTERPOLATE(array[...,i].astype(float), Decode[2*i], Decode[2*i + 1], 0, 255)
array = np.clip(np.round(array), 0, 255).astype(np.uint8)
return array if N > 1 else array[...,0]
# ========================================================================== class PdfDecodedImage
class PdfImage(AttrDict):
# To do:
# 1) Lab color
# 2) color reductions
formats = ['array', 'pil', 'tiff', 'jbig2', 'jpeg', 'jp2', 'png']
def __init__(self,
obj:IndirectPdfDict = None,
pil:Image.Image = None,
array:np.ndarray = None,
jpeg:bytes = None,
jp2:bytes = None):
'''
Creates a PdfImage.
'''
if sum(1 for x in [obj, pil, array,jp2,jpeg] if x is not None) != 1:
raise ValueError(f'exactly one of the [pil, array, obj] arguments should be given to constructor')
self.bpc = None
self.ColorSpace = None
self.dpi = None
self.pil = pil
self.array = array
self.jpeg = jpeg
self.jp2 = None
self.Decode = None
self.Mask = None
self.SMask = None
self.isRendered = False
if obj:
assert obj.Subtype in ['/Image', PdfName.Image]
if obj.stream == None: raise ValueError(f'image has no stream: {obj}')
obj = PdfFilter.uncompress(obj)
self.Decode = obj.Decode
self.ColorSpace = PdfImage.xobject_get_cs(obj)
self.bpc = PdfImage.xobject_get_bpc(obj)
def toBytes(s:str): return s.encode('Latin-1')
stream = toBytes(obj.stream)
if obj.Filter == None:
width, height = int(obj.Width), int(obj.Height)
cpp = self.get_cpp()
# Sometimes /BitsPerComponent is incorrect
bytesPerLine = len(stream) / height
if bytesPerLine == int(bytesPerLine):
bpc_implied = (bytesPerLine * 8) / (width * cpp) if len(stream) > 1 else 1
if bpc_implied != self.bpc and int(bpc_implied) == bpc_implied:
warn(f'replacing bad image xobject\'s bpc = {self.bpc} with the implied bpc = {int(bpc_implied)}')
self.bpc = int(bpc_implied)
array = PdfFilter.unpack_pixels(stream, width, cpp, self.bpc, truncate = True)
if array.shape[0] > height:
warn(f'more rows in stream than expected: {array.shape[0]} vs {height}; truncating')
array = array[:height]
if array.shape[0] != height:
raise ValueError(f'image height mismatch: expected {height}, read {array.shape[0]}, bpc = {self.bpc}')
array = SImage.normalize(array)
if self.bpc == 1: array = array.astype(bool)
self.set_array(array)
elif obj.Filter == '/CCITTFaxDecode':
parm = obj.DecodeParms
assert parm
K = int(parm.K or '0')
EncodedByteAlign = parm.EncodedByteAlign == PdfObject('true')
if K == -1 and EncodedByteAlign:
from pdfrwx.ccitt import Group4Decoder
decoder = Group4Decoder()
Columns = int(parm.Columns)
result = decoder.decode(data = stream,
Columns = Columns,
EncodedByteAlign = EncodedByteAlign)
width, height = int(obj.Width), int(obj.Height)
pil = Image.frombytes('1',(width,height),result)
if parm.BlackIs1 != PdfObject('true'):
pil = ImageChops.invert(pil)
self.set_pil(pil)
else:
if EncodedByteAlign:
warn(f'*** /CCITTFaxDecode Group3 (T4) decompression with /EncodedByteAlign is in beta-testing, check results ***')
header = PdfImage._tiff_make_header(obj)
self.set_pil(Image.open(BytesIO(header + stream)))
elif obj.Filter == '/JBIG2Decode':
jbig2_locals = stream
try: jbig2_globals = toBytes(PdfFilter.uncompress(obj.DecodeParms.JBIG2Globals).stream)
except: jbig2_globals = None
self.set_pil(PdfImage._jbig2_read([jbig2_locals, jbig2_globals]))
elif obj.Filter == '/DCTDecode':
pil = Image.open(BytesIO(stream))
self.set_pil(pil)
elif obj.Filter == '/JPXDecode':
self.read_jp2_to_array(stream)
else:
raise ValueError(f'bad filter: {obj.Filter}')
if obj.DecodeParms and obj.Filter in ['/DCTDecode', '/JPXDecode', None]:
warn(f'ignoring /DecodeParms: {obj.DecodeParms}')
# Handle transparency
self.Mask = obj.Mask
self.SMask = obj.SMask
# Invert /DeviceCMYK & /DeviceN JPEGs
# cs_name = PdfColorSpace.get_name(self.ColorSpace)
if self.pil and self.pil.mode == 'CMYK' and self.pil.format == 'JPEG':
msg(f'inverting CMYK JPEG after decoding')
self.set_pil(ImageChops.invert(self.pil))
else:
if jpeg:
self.pil = Image.open(BytesIO(jpeg))
if self.pil:
# Handle transparency
if self.pil.mode in ['PA','LA','RGBA']:
self.pil, alpha = PdfImage._pil_split_alpha(pil)
self.SMask = PdfImage(pil = alpha).encode()
self.ColorSpace = PdfImage._pil_get_colorspace(self.pil)
self.bpc = 1 if self.pil.mode == '1' else 8
self.dpi = self.pil.info.get('dpi')
if jp2:
self.read_jp2_to_array(jp2)
self.dpi = Image.open(BytesIO(jp2)).info.get('dpi')
if array is not None:
SImage.validate(array)
N = SImage.nColors(array)
self.ColorSpace = PdfName.DeviceGray if N == 1 \
else PdfName.DeviceRGB if N == 3 \
else PdfName.DeviceCMYK if N == 4 \
else None
self.bpc = 1 if SImage.isBitonal(array) else 8
# -------------------------------------------------------------------------------------- Basic functions
def w(self):
'''Returns width'''
return self.array.shape[1] if self.array is not None else self.pil.width
def h(self):
'''Returns height.'''
return self.array.shape[0] if self.array is not None else self.pil.height
def get_cpp(self):
'''Returns components per pixel.'''
return PdfColorSpace.get_cpp(self.ColorSpace)
def get_mode(self):
'''Returns a PIL mode that is appropriate for the current colorspace and bpc values.'''
return PdfColorSpace.get_mode(self.ColorSpace, self.bpc)
def to_bytes(self):
'''Returns pixel intensities as a bytes object.'''
return self.pil.tobytes() if self.pil else PdfFilter.pack_pixels(self.array, self.bpc)
def invert(self):
'''Inverts image'''
if self.pil: self.set_pil(ImageChops.invert(self.pil))
elif self.array is not None: self.set_array(SImage.invert(self.array))
else: raise ValueError(f'bad PdfImage: {self}')
def __str__(self):
'''Returns a string representation of the image that contains
various image parameters in a compact format'''
attrs = [a for a in ['pil','array','jp2','mask'] if self.__getattr__(a) is not None]
if self.isRendered: attrs.append('isRendered')
attrs = '/'.join(attrs)
return f'{self.w()}x{self.h()}, DPI={self.dpi}, CS={PdfColorSpace.get_name(self.ColorSpace)}' \
+ f', BPC={self.bpc}, STATE: {attrs}'
# -------------------------------------------------------------------------------------- render()
def render(self, pdfPage:PdfDict = None, debug:bool = False):
'''
'''
if self.isRendered:
warn('image already rendered; skipping')
return
if debug: msg('rendering started')
# Default colorspace
try:
cs2cs = {'/DeviceGray':'/DefaultGray', '/DeviceRGB':'/DefaultRGB', '/DeviceCMYK':'/DefaultCMYK'}
cs = pdfPage.Resources.ColorSpace[cs2cs[self.ColorSpace]] or self.ColorSpace
if cs != None and debug:
msg(f'Page default colorspace: {PdfColorSpace.toStr(self.ColorSpace)} --> {PdfColorSpace.toStr(cs)}')
except:
cs = self.ColorSpace
if debug: msg(f'applying image colorspace: {PdfColorSpace.toStr(cs)}')
self.apply_colorspace(cs, self.SMask) # Mask is needed to unmultiply alpha if necessary
# # Apply page default colorspace
# try:
# # This will fail if cs is not among the entries of the page default colorspaces dict
# cs2cs = {'/DeviceGray':'/DefaultGray', '/DeviceRGB':'/DefaultRGB', '/DeviceCMYK':'/DefaultCMYK'}
# default_cs = pdfPage.Resources.ColorSpace[cs2cs[self.ColorSpace]]
# msg(f'applying page default colorspace: {PdfColorSpace.toStr(default_cs)}')
# self.apply_colorspace(default_cs)
# except: pass
self.isRendered = True
if debug: msg('rendering ended')
# -------------------------------------------------------------------------------------- apply_colorspace()
def apply_colorspace(self, cs:CS_TYPE, mask:PdfDict = None):
'''
'''
actualDecode = PdfDecodeArray.get_actual(self.Decode, cs, self.bpc)
defaultDecode = PdfDecodeArray.get_default(cs, self.bpc)
cs_name = PdfColorSpace.get_name(cs)
if cs_name == '/Indexed':
# In the /Indexed color space, all color space transformations are performed on the palette.
# Note: palette_cs is never /Indexed (see Adobe PDF Ref.)
# PDF standard allows for remapping of palette indices via Decode arrays (why oh why?)
if actualDecode != defaultDecode:
warn(f'decoding indices in the /Indexed colorspace; this is strange, check results')
array = self.get_array()
array = PdfDecodeArray.decode(array, actualDecode, self.bpc)
array = np.clip(np.round(array),0,255).astype('uint8') # clip right away: no encoding step later
self.set_array(array)
self.bpc = 8
self.Decode = None
# Transform the palette
palette_cs, palette_array = PdfColorSpace.get_palette(cs)
if PdfColorSpace.get_name(palette_cs) in ['/Separation', '/DeviceN', '/NChannel']:
# Apply palette_cs to palette_array; both palette_array & palette_cs can change
palette_decode = PdfDecodeArray.get_default(palette_cs, 8)
palette_array = np.array([palette_array])
palette_cs, palette_array = PdfColorSpace.reduce(palette_cs, palette_array, palette_decode, 8, mask)
palette_array = palette_array[0]
# Create new /Indexed colorspace
self.ColorSpace = PdfArray([PdfName.Indexed, palette_cs, palette_array.shape[0], palette_array.tobytes()])
# Reduce palette; comment this of if you do not want render() to reduce palettes
self.ColorSpace = palette_cs
self.set_array(palette_array[self.get_array()])
self.bpc = 8
self.Decode = None
elif cs_name in ['/Separation', '/DeviceN', '/NChannel'] \
or actualDecode != defaultDecode \
or mask != None and mask.Matte != None:
self.ColorSpace, array = PdfColorSpace.reduce(cs, self.get_array(), actualDecode, self.bpc, mask)
self.set_array(array)
self.bpc = 8
self.Decode = None
# -------------------------------------------------------------------------------------- change_mode()
def change_mode(self, mode:str, intent:str = '/Perceptual'):
'''
Changes image mode. The mode argument can be any one of: 'L', 'RGB', 'CMYK'
'''
assert self.isRendered
if mode not in ['L', 'RGB', 'CMYK']: raise ValueError(f'cannot convert to mode: {mode}')
if mode == self.get_mode() and self.ColorSpace in [PdfName.DeviceGray, PdfName.DeviceRGB, PdfName.DeviceCMYK]:
warn(f'old and new modes are the same: {mode}')
return False
# Whatever the case below, either bpc will be 8 or exception will be raised
# and so it's safe to set bpc already at this point
self.bpc = 8
if self.get_mode() == '1':
if mode == 'L':
if self.array: self.set_array(SImage.toGray(self.array))
elif self.pil: self.set_pil(self.pil.convert('L'))
else: raise ValueError(f'bad PdfImage: {self}')
self.ColorSpace = '/DeviceGray'
return True
elif mode == 'RGB':
if self.array: self.set_array(SImage.toColor(self.array))
elif self.pil: self.set_pil(self.pil.convert('RGB'))
else: raise ValueError(f'bad PdfImage: {self}')
self.ColorSpace = '/DeviceRGB'
return True
else:
warn(f'cannot convert {"1"} --> {mode}')
return False
# Render
pil = self.get_pil()
# Get intent
intents = {'/Perceptual': ImageCms.Intent.PERCEPTUAL,
'/RelativeColorimetric': ImageCms.Intent.RELATIVE_COLORIMETRIC,
'/Saturation': ImageCms.Intent.SATURATION,
'/AbsoluteColorimetric': ImageCms.Intent.ABSOLUTE_COLORIMETRIC }
renderingIntent = intents.get(intent, ImageCms.Intent.PERCEPTUAL)
msg(f'converting {pil.mode} --> {mode} (intent = {intent})')
# Standard sRGB & CMYK profiles
cmyk_profile = ImageCms.ImageCmsProfile(BytesIO(CMYK_DEFAULT_ICC_PROFILE))
srgb_profile = ImageCms.createProfile('sRGB')
# Input profile
icc_profile = PdfColorSpace.get_icc_profile(self.ColorSpace)
input_profile = ImageCms.ImageCmsProfile(BytesIO(icc_profile)) if icc_profile \
else cmyk_profile if pil.mode == 'CMYK' \
else srgb_profile if pil.mode in ['RGB', 'P'] else None
if not input_profile:
warn(f'cannot convert {self.get_mode()} --> {mode}')
return False
# Output profile
output_profile = cmyk_profile if mode == 'CMYK' else srgb_profile if mode == 'RGB' else None
if not output_profile:
# Conversion to L: first convert to RGB to account for input_profile, then to L
# image = ImageCms.profileToProfile(image, input_profile, srgb_profile,
# renderingIntent = renderingIntent, outputMode='RGB')
pil = pil.convert('L')
else:
pil = ImageCms.profileToProfile(pil, input_profile, output_profile,
renderingIntent = renderingIntent, outputMode=mode)
if 'icc_profile' in pil.info: del pil.info['icc_profile']
self.ColorSpace = PdfName.DeviceGray if pil.mode == 'L' \
else PdfName.DeviceRGB if pil.mode == 'RGB' \
else PdfName.DeviceCMYK
# else PdfColorSpace.make_icc_based_colorspace(CMYK_DEFAULT_ICC_PROFILE, N=4)
self.set_pil(pil)
# -------------------------------------------------------------------------------------- get_pil()
def get_pil(self):
'''
Creates a PIL Image representation in self.pil, if not yet created, and returns it.
'''
if not self.pil:
assert self.array is not None
assert self.ColorSpace is not None
assert self.bpc is not None
msg('array -> pil')
mode = PdfColorSpace.get_mode(self.ColorSpace, self.bpc)
# A PIL bug: https://stackoverflow.com/questions/50134468/convert-boolean-numpy-array-to-pillow-image
self.pil = Image.fromarray(self.array, mode = mode) if mode != '1' \
else Image.frombytes(mode='1', size=self.array.shape[::-1], data=np.packbits(self.array, axis=1))
return self.pil
# -------------------------------------------------------------------------------------- get_array()
def get_array(self):
'''
Creates a numpy array representation in self.array, if not yet created, and returns it.
'''
if self.array is None:
assert self.pil
msg('pil -> array')
self.array = np.array(self.pil)
SImage.validate(self.array)
return self.array
# -------------------------------------------------------------------------------------- set_pil()
def set_pil(self, pil:Image.Image):
'''
Sets self.pil to the given PIL image, and self.array & self.jp2 to None
'''
self.pil = pil
self.array = None
self.jp2 = None
self.jpeg = None
# -------------------------------------------------------------------------------------- set_array()
def set_array(self, array:np.ndarray):
'''
Sets self.array to the given numpy image array, and self.pil, self.jpeg & self.jp2 to None
'''
self.pil = None
self.array = array
self.jp2 = None
self.jpeg = None
# -------------------------------------------------------------------------------------- set_jp2()
def read_jp2_to_array(self, jp2:bytes):
'''
Reads jp2 into self.array and sets self.bpc.
If self.ColorSpace is None it is set to the internal colorspace of the jp2 image.
Also, self.jp2 is set to jp2, unless self.ColorSpace == ['/Indexed', ..].
Having self.array, self.ColorSpace and self.bpc set allows for subsequent image analysis/modification.
This leaves self.jp2 as a kind of storage for the original JPEG2000 file's bytes
in case we want to save the jp2 image data without re-encoding.
Note: when self.ColorSpace is an /Indexed colorspace, self.array will be read as
a /DeviceRGB or /DeviceCMYK colorspace, and therefore, and therefore 1) self.ColorSpace
will be set to /DeviceRGB or /DeviceCMYK to reflect that; 2) jp2 will not be stored
in self.jp2.
'''
self.array, jp2_cs, self.bpc = PdfImage._jp2_read(jp2)
cs = self.ColorSpace
isIndexed = isinstance(cs, PdfArray) and cs[0] == '/Indexed'
if not isIndexed:
self.jp2 = jp2
if not cs or isIndexed: # obj.ColorSpace overrides internal JPX colorspace
self.ColorSpace = jp2_cs
self.Decode = None
self.pil = None
self.jpeg = None
# -------------------------------------------------------------------------------------- resize()
def resize(self, width:int, height:int):
'''
Resize the image to the given dimensions.
'''
self.set_pil(self.get_pil().resize((width, height)))
# -------------------------------------------------------------------------------------- saveAs
def saveAs(self, Format:str,
Q:float = None,
CR:float = None,
optimize = True,
render = False,
intent:str = '/Perceptual',
embedProfile:bool = True,
invertCMYK = False):
'''
Returns a tuple `(imageStream[bytes], fileExtension[str])`.
The encoding is done in the given `Format` using the
`Q` (quality), `CR` (compression ratio) and `optimize` parameters.
The image has to be rendered first in order to produce a faithful representation.
'''
ext = {'TIFF':'.tif', 'PNG':'.png', 'JPEG':'.jpg', 'JPEG2000':'.jp2', 'JBIG2':'jb2'}
addAlpha = render and (self.Mask or self.SMask)
if Format == 'JPEG' and addAlpha:
raise ValueError(f'cannot save an image transparency as JPEG')
if Format == 'auto':
Format = self.pil.format if self.pil and self.pil.format in ext \
else 'JPEG2000' if self.jp2 \
else 'JPEG' if self.jpeg \
else 'TIFF'
if addAlpha and Format == 'JPEG':
Format = 'TIFF'
if Format not in ext: raise ValueError(f'cannot save in format: {Format}')
# Save original JPEG bytes object whenever possible
if Format == 'JPEG' and self.jpeg and not render and not addAlpha and Q == None \
and (self.get_mode() != 'CMYK' or not invertCMYK):
msg(f'saving original (unmodified) JPEG file')
return self.jpeg, '.jpg'
if addAlpha:
msg('rendering alpha')
alpha = PdfImage(obj = self.Mask or self.SMask)
alpha.render()
if alpha.w() != self.w() or alpha.h() != self.h():
if self.w() * self.h() > alpha.w() * alpha.h():
msg(f'resizing alpha to fit image')
alpha.resize(self.w(), self.h())
else:
msg(f'resizing image to fit alpha')
self.resize(alpha.w(), alpha.h())
# # ???????????????????????????????
# if alpha.mode == '1':
# alpha = alpha.convert('L')
if Format == 'JPEG2000':
if self.jp2:
stream = self.jp2
else:
assert Q or CR
if Q: assert 0 < Q <= 100
if CR: assert CR > 1
stream = PdfImage._jp2_write(array = self.get_array(),
alpha = alpha.get_array() if addAlpha else None,
cs = self.ColorSpace,
Q = Q, CR = CR)
else:
# Create pil
pil = self.get_pil()
if render:
msg('rendering pil')
self.render()
if addAlpha and self.get_mode() not in ['L', 'RGB']:
self.change_mode('RGB' if self.get_mode() != '1' else 'L', intent)
pil = self.get_pil()
PdfImage._pil_set_colorspace(pil, self.ColorSpace)
if addAlpha:
msg('adding alpha')
# alpha.render()
assert alpha.get_cpp() == 1
alpha.change_mode('RGB' if alpha.get_mode() != '1' else 'L', intent)
alpha_pil = alpha.get_pil()
# invert bitonal masks
if self.Mask and self.Mask.ImageMask == PdfObject('true'):
alpha_pil = ImageChops.invert(alpha_pil)
PdfImage._pil_set_colorspace(alpha_pil, alpha.ColorSpace)
pil.putalpha(alpha_pil)
if invertCMYK and pil.mode == 'CMYK' and Format == 'JPEG':
msg('inverting CMYK JPEG before encoding')
pil = ImageChops.invert(pil)
bs = BytesIO()
Q = Q if Q else 'keep' if pil.format == 'JPEG' and Format == 'JPEG' else 100
msg(f'saving with Format = {Format}, Q = {Q}')
# tiff_compression = 'group4' if pil.mode == '1' else 'tiff_lzw' if Format == 'TIFF' else None
tiff_compression = 'group4' if pil.mode == '1' else 'tiff_adobe_deflate' if Format == 'TIFF' else None
icc_profile = pil.info.get('icc_profile') if pil.info and embedProfile else None
dpi = self.dpi if self.dpi not in (None, (1,1)) else (72,72)
if Format == 'JPEG':
pil.save(bs, Format, quality=Q, optimize = optimize, icc_profile = icc_profile, info = pil.info, dpi=dpi)
elif Format == 'PNG':
pil.save(bs, Format, optimize = optimize, icc_profile = icc_profile)
elif Format == 'TIFF':
pil.save(bs, Format, compression = tiff_compression, icc_profile = icc_profile)
else: