/
pil_io.py
276 lines (230 loc) · 8.72 KB
/
pil_io.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
"""
PIL IO module.
"""
from __future__ import absolute_import, unicode_literals
import logging
import io
from psd_tools.constants import ColorMode, ChannelID, Resource
from .numpy_io import has_transparency, get_transparency_index
logger = logging.getLogger(__name__)
def get_color_mode(mode):
"""Convert PIL mode to ColorMode."""
name = mode.upper()
name = name.rstrip('A') # Trim alpha.
name = {'1': 'BITMAP', 'L': 'GRAYSCALE'}.get(name, name)
return getattr(ColorMode, name)
def get_pil_mode(color_mode, alpha=False):
"""Get PIL mode from ColorMode."""
name = {
ColorMode.GRAYSCALE: 'L',
ColorMode.BITMAP: '1',
ColorMode.DUOTONE: 'L',
ColorMode.INDEXED: 'P',
ColorMode.MULTICHANNEL: 'L', # TODO: Cannot support in PIL.
}.get(color_mode, color_mode.name)
if alpha and name in ('L', 'RGB'):
name += 'A'
return name
def get_pil_channels(pil_mode):
"""Get the number of channels for PIL modes."""
return {
'1': 1,
'L': 1,
'P': 1,
'RGB': 3,
'CMYK': 4,
'YCbCr': 3,
'LAB': 3,
'HSV': 3,
'I': 1,
'F': 1,
}.get(pil_mode, 3)
def convert_image_data_to_pil(psd, channel, apply_icc):
"""Convert ImageData to PIL Image.
"""
from PIL import Image
assert channel is None or channel < psd.channels, (
'Invalid channel specified: %s' % channel
)
# Support alpha channel via ChannelID enum.
if channel == ChannelID.TRANSPARENCY_MASK:
channel = get_pil_channels(get_pil_mode(psd.color_mode))
if channel >= psd.channels:
return None
alpha = None
icc = None
channel_data = psd._record.image_data.get_data(psd._record.header)
size = (psd.width, psd.height)
if channel is None:
channels = [_create_image(size, c, psd.depth) for c in channel_data]
if has_transparency(psd):
alpha = channels[get_transparency_index(psd)]
if psd.color_mode == ColorMode.INDEXED:
image = channels[0]
image.putpalette(psd._record.color_mode_data.interleave())
elif psd.color_mode == ColorMode.MULTICHANNEL:
image = channels[0] # Multi-channel mode is a collection of alpha.
else:
mode = get_pil_mode(psd.color_mode)
image = Image.merge(mode, channels[:get_pil_channels(mode)])
if apply_icc and (Resource.ICC_PROFILE in psd.image_resources):
icc = psd.image_resources.get_data(Resource.ICC_PROFILE)
else:
image = _create_image(size, channel_data[channel], psd.depth)
if not image:
return None
image = post_process(image, alpha, icc)
return _remove_white_background(image)
def convert_layer_to_pil(layer, channel, apply_icc):
"""Convert Layer to PIL Image."""
alpha = None
icc = None
if channel is None:
image = _merge_channels(layer)
alpha = _get_channel(layer, ChannelID.TRANSPARENCY_MASK)
if apply_icc and (Resource.ICC_PROFILE in layer._psd.image_resources):
icc = layer._psd.image_resources.get_data(Resource.ICC_PROFILE)
else:
image = _get_channel(layer, channel)
if not image or (channel is not None and channel < 0):
return image # Return None, alpha or mask.
return post_process(image, alpha, icc)
def post_process(image, alpha, icc_profile):
# Fix inverted CMYK.
if image.mode == 'CMYK':
from PIL import ImageChops
image = ImageChops.invert(image)
if icc_profile:
image = _apply_icc(image, icc_profile)
# In Pillow, alpha channel is only available in RGB or L.
if alpha and image.mode in ('RGB', 'L'):
image.putalpha(alpha)
return image
def convert_pattern_to_pil(pattern):
"""Convert Pattern to PIL Image."""
from PIL import Image
mode = get_pil_mode(pattern.image_mode)
# The order is different here.
size = pattern.data.rectangle[3], pattern.data.rectangle[2]
channels = [
_create_image(size, c.get_data(), c.pixel_depth).convert('L')
for c in pattern.data.channels if c.is_written
]
alpha = None
channel_size = get_pil_channels(mode)
if mode in ('RGB', 'L') and len(channels) > channel_size:
alpha = channels[channel_size]
if mode == 'P':
image = channels[0]
image.putpalette([x for rgb in pattern.color_table for x in rgb])
else:
image = Image.merge(mode, channels[:channel_size])
return post_process(image, alpha, None) # TODO: icc support?
def convert_thumbnail_to_pil(thumbnail, mode='RGB'):
"""Convert thumbnail resource."""
from PIL import Image
if thumbnail.fmt == 0:
size = (thumbnail.width, thumbnail.height)
stride = thumbnail.widthbytes
return Image.frombytes(
'RGBX', size, thumbnail.data, 'raw', mode, stride
)
elif thumbnail.fmt == 1:
return Image.open(io.BytesIO(thumbnail.data))
else:
raise ValueError('Unknown thumbnail format %d' % (thumbnail.fmt))
def _merge_channels(layer):
from PIL import Image
mode = get_pil_mode(layer._psd.color_mode)
channels = [
_get_channel(layer, info.id) for info in layer._record.channel_info
if info.id >= 0
]
if any(image is None for image in channels):
return None
channels = _check_channels(channels, layer._psd.color_mode)
return Image.merge(mode, channels)
def _get_channel(layer, channel):
if channel == ChannelID.USER_LAYER_MASK:
width = layer.mask._data.right - layer.mask._data.left
height = layer.mask._data.bottom - layer.mask._data.top
elif channel == ChannelID.REAL_USER_LAYER_MASK:
width = layer.mask._data.real_right - layer.mask._data.real_left
height = layer.mask._data.real_bottom - layer.mask._data.real_top
else:
width, height = layer.width, layer.height
index = {info.id: i for i, info in enumerate(layer._record.channel_info)}
if channel not in index:
return None
depth = layer._psd.depth
channel_data = layer._channels[index[channel]]
if width == 0 or height == 0 or len(channel_data.data) == 0:
return None
channel = channel_data.get_data(width, height, depth, layer._psd.version)
return _create_image((width, height), channel, depth)
def _create_image(size, data, depth):
from PIL import Image
if depth == 8:
return Image.frombytes('L', size, data, 'raw')
elif depth == 16:
image = Image.frombytes('I', size, data, 'raw', 'I;16B')
return image.point(lambda x: x * (1. / 256.)).convert('L')
elif depth == 32:
image = Image.frombytes('F', size, data, 'raw', 'F;32BF')
# TODO: Check grayscale range.
return image.point(lambda x: x * (256.)).convert('L')
elif depth == 1:
return Image.frombytes('1', size, data, 'raw', '1;I')
else:
raise ValueError('Unsupported depth: %g' % depth)
def _check_channels(channels, color_mode):
expected_channels = ColorMode.channels(color_mode)
if len(channels) > expected_channels:
# Seems possible when FilterMask is attached.
logger.debug(
'Channels mismatch: expected %g != given %g' %
(expected_channels, len(channels))
)
channels = channels[:expected_channels]
elif len(channels) < expected_channels:
raise ValueError(
'Channels mismatch: expected %g != given %g' %
(expected_channels, len(channels))
)
return channels
def _apply_icc(image, icc_profile):
"""Apply ICC Color profile."""
from io import BytesIO
try:
from PIL import ImageCms
except ImportError:
logger.debug(
'ICC profile found but not supported. Install little-cms.'
)
return image
try:
in_profile = ImageCms.ImageCmsProfile(BytesIO(icc_profile))
out_profile = ImageCms.createProfile('sRGB')
outputMode = image.mode if image.mode in ('L', 'LA', 'RGBA') else 'RGB'
return ImageCms.profileToProfile(image, in_profile, out_profile, outputMode=outputMode)
except ImageCms.PyCMSError as e:
logger.warning('PyCMSError: %s' % (e))
return image
def _remove_white_background(image):
"""Remove white background in the preview image."""
from PIL import ImageMath, Image
if image.mode == "RGBA":
bands = image.split()
a = bands[3]
rgb = [
ImageMath.eval(
'convert('
'float(x + a - 255) * 255.0 / float(max(a, 1)) * '
'float(min(a, 1)) + float(x) * float(1 - min(a, 1))'
', "L")',
x=x,
a=a
) for x in bands[:3]
]
return Image.merge(bands=rgb + [a], mode="RGBA")
return image