Skip to content

Commit 5fc6cdb

Browse files
committed
Allow plugins to specify their supported modes
1 parent aee5d22 commit 5fc6cdb

8 files changed

Lines changed: 130 additions & 59 deletions

File tree

Tests/test_file_gif.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -786,11 +786,12 @@ def test_save_I(tmp_path):
786786
assert_image_equal(reloaded.convert("L"), im.convert("L"))
787787

788788

789-
def test_save_wrong_modes(self):
789+
def test_save_wrong_modes():
790790
out = BytesIO()
791791
for mode in ["CMYK"]:
792792
img = Image.new(mode, (20, 20))
793-
self.assertRaises(ValueError, img.save, out, "GIF")
793+
with pytest.raises(ValueError):
794+
img.save(out, "GIF")
794795

795796
for mode in ["CMYK", "LA"]:
796797
img = Image.new(mode, (20, 20))

Tests/test_file_webp.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,6 @@
1212
skip_unless_feature,
1313
)
1414

15-
from io import BytesIO
16-
1715
try:
1816
from PIL import _webp
1917

@@ -88,7 +86,7 @@ def _roundtrip(self, tmp_path, mode, epsilon, args={}):
8886
assert_image_similar(image, target, epsilon)
8987

9088
def test_save_convert_mode(self):
91-
out = BytesIO()
89+
out = io.BytesIO()
9290
for mode in ["CMYK", "I", "L", "LA", "P"]:
9391
img = Image.new(mode, (20, 20))
9492
img.save(out, "WEBP", convert_mode=True)

Tests/test_image.py

Lines changed: 58 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import io
22
import os
33
import shutil
4+
import sys
45
import tempfile
56

67
import pytest
@@ -103,8 +104,6 @@ def test_width_height(self):
103104
im.size = (3, 4)
104105

105106
def test_invalid_image(self):
106-
import io
107-
108107
im = io.BytesIO(b"")
109108
with pytest.raises(UnidentifiedImageError):
110109
Image.open(im)
@@ -384,14 +383,67 @@ def test_registered_extensions(self):
384383
for ext in [".cur", ".icns", ".tif", ".tiff"]:
385384
assert ext in extensions
386385

387-
def test_no_convert_mode(self):
388-
self.assertTrue(not hasattr(TiffImagePlugin, "_convert_mode"))
389-
390-
temp_file = self.tempfile("temp.tiff")
386+
def test_supported_modes(self):
387+
for format in Image.MIME.keys():
388+
try:
389+
save_handler = Image.SAVE[format]
390+
except KeyError:
391+
continue
392+
plugin = sys.modules[save_handler.__module__]
393+
if not hasattr(plugin, "_supported_modes"):
394+
continue
395+
396+
# Check that the supported modes list is accurate
397+
supported_modes = plugin._supported_modes()
398+
for mode in [
399+
"1",
400+
"L",
401+
"P",
402+
"RGB",
403+
"RGBA",
404+
"CMYK",
405+
"YCbCr",
406+
"LAB",
407+
"HSV",
408+
"I",
409+
"F",
410+
"LA",
411+
"La",
412+
"RGBX",
413+
"RGBa",
414+
]:
415+
out = io.BytesIO()
416+
im = Image.new(mode, (100, 100))
417+
if mode in supported_modes:
418+
im.save(out, format)
419+
else:
420+
with pytest.raises(Exception):
421+
im.save(out, format)
422+
423+
def test_no_supported_modes_method(self, tmp_path):
424+
assert not hasattr(TiffImagePlugin, "_supported_modes")
425+
426+
temp_file = str(tmp_path / "temp.tiff")
391427

392428
im = hopper()
393429
im.save(temp_file, convert_mode=True)
394430

431+
def test_convert_mode(self):
432+
for mode, modes in [["P", []], ["P", ["P"]]]: # no modes, same mode
433+
im = Image.new(mode, (100, 100))
434+
assert im._convert_mode(modes) is None
435+
436+
for mode, modes in [
437+
["P", ["RGB"]],
438+
["P", ["L"]], # converting to a non-preferred mode
439+
["LA", ["P"]],
440+
["I", ["L"]],
441+
["RGB", ["L"]],
442+
["RGB", ["CMYK"]],
443+
]:
444+
im = Image.new(mode, (100, 100))
445+
assert im._convert_mode(modes) is not None
446+
395447
def test_effect_mandelbrot(self):
396448
# Arrange
397449
size = (512, 512)

src/PIL/GifImagePlugin.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -872,11 +872,8 @@ def write(self, data):
872872
return fp.data
873873

874874

875-
def _convert_mode(im):
876-
return {
877-
'LA':'P',
878-
'CMYK':'RGB'
879-
}.get(im.mode)
875+
def _supported_modes():
876+
return ["RGB", "RGBA", "P", "I", "F", "LA", "L", "1"]
880877

881878

882879
# --------------------------------------------------------------------

src/PIL/Image.py

Lines changed: 46 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2129,16 +2129,18 @@ def save(self, fp, format=None, **params):
21292129

21302130
if format.upper() not in SAVE:
21312131
init()
2132-
if params.pop('save_all', False):
2132+
if params.pop("save_all", False):
21332133
save_handler = SAVE_ALL[format.upper()]
21342134
else:
21352135
save_handler = SAVE[format.upper()]
21362136

2137-
if params.get('convert_mode'):
2137+
if params.get("convert_mode"):
21382138
plugin = sys.modules[save_handler.__module__]
2139-
converted_im = self._convert_mode(plugin, params)
2140-
if converted_im:
2141-
return converted_im.save(fp, format, **params)
2139+
if hasattr(plugin, "_supported_modes"):
2140+
modes = plugin._supported_modes()
2141+
converted_im = self._convert_mode(modes, params)
2142+
if converted_im:
2143+
return converted_im.save(fp, format, **params)
21422144

21432145
self.encoderinfo = params
21442146
self.encoderconfig = ()
@@ -2158,32 +2160,57 @@ def save(self, fp, format=None, **params):
21582160
if open_fp:
21592161
fp.close()
21602162

2161-
def _convert_mode(self, plugin, params):
2162-
if not hasattr(plugin, '_convert_mode'):
2163+
def _convert_mode(self, modes, params={}):
2164+
if not modes or self.mode in modes:
21632165
return
2164-
new_mode = plugin._convert_mode(self)
2165-
if self.mode == 'LA' and new_mode == 'P':
2166-
alpha = self.getchannel('A')
2166+
if self.mode == "P":
2167+
preferred_modes = []
2168+
if "A" in self.im.getpalettemode():
2169+
preferred_modes.append("RGBA")
2170+
preferred_modes.append("RGB")
2171+
else:
2172+
preferred_modes = {
2173+
"CMYK": ["RGB"],
2174+
"RGB": ["CMYK"],
2175+
"RGBX": ["RGB"],
2176+
"RGBa": ["RGBA", "RGB"],
2177+
"RGBA": ["RGB"],
2178+
"LA": ["RGBA", "P", "L"],
2179+
"La": ["LA", "L"],
2180+
"L": ["RGB"],
2181+
"F": ["I"],
2182+
"I": ["L", "RGB"],
2183+
"1": ["L"],
2184+
"YCbCr": ["RGB"],
2185+
"LAB": ["RGB"],
2186+
"HSV": ["RGB"],
2187+
}.get(self.mode, [])
2188+
for new_mode in preferred_modes:
2189+
if new_mode in modes:
2190+
break
2191+
else:
2192+
new_mode = modes[0]
2193+
if self.mode == "LA" and new_mode == "P":
2194+
alpha = self.getchannel("A")
21672195
# Convert the image into P mode but only use 255 colors
21682196
# in the palette out of 256.
2169-
im = self.convert('L') \
2170-
.convert('P', palette=ADAPTIVE, colors=255)
2197+
im = self.convert("L").convert("P", palette=ADAPTIVE, colors=255)
21712198
# Set all pixel values below 128 to 255, and the rest to 0.
21722199
mask = eval(alpha, lambda px: 255 if px < 128 else 0)
21732200
# Paste the color of index 255 and use alpha as a mask.
21742201
im.paste(255, mask)
21752202
# The transparency index is 255.
2176-
im.info['transparency'] = 255
2203+
im.info["transparency"] = 255
21772204
return im
21782205

2179-
elif self.mode == 'I':
2180-
im = self.point([i//256 for i in range(65536)], 'L')
2181-
return im.convert(new_mode) if new_mode != 'L' else im
2206+
elif self.mode == "I":
2207+
im = self.point([i // 256 for i in range(65536)], "L")
2208+
return im.convert(new_mode) if new_mode != "L" else im
21822209

2183-
elif self.mode in ('RGBA', 'LA') and new_mode in ('RGB', 'L'):
2184-
fill_color = params.get('fill_color', 'white')
2210+
elif self.mode in ("RGBA", "LA") and new_mode in ("RGB", "L"):
2211+
fill_color = params.get("fill_color", "white")
21852212
background = new(new_mode, self.size, fill_color)
2186-
background.paste(self, self.getchannel('A'))
2213+
background.paste(self, self.getchannel("A"))
21872214
return background
21882215

21892216
elif new_mode:

src/PIL/JpegImagePlugin.py

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -801,15 +801,8 @@ def jpeg_factory(fp=None, filename=None):
801801
return im
802802

803803

804-
def _convert_mode(im):
805-
mode = im.mode
806-
if mode == 'P':
807-
return 'RGBA' if 'A' in im.im.getpalettemode() else 'RGB'
808-
return {
809-
'RGBA':'RGB',
810-
'LA':'L',
811-
'I':'L'
812-
}.get(mode)
804+
def _supported_modes():
805+
return ["RGB", "CMYK", "YCbCr", "RGBX", "L", "1"]
813806

814807

815808
# ---------------------------------------------------------------------

src/PIL/PngImagePlugin.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1355,10 +1355,8 @@ def append(fp, cid, *data):
13551355
return fp.data
13561356

13571357

1358-
def _convert_mode(im):
1359-
return {
1360-
'CMYK':'RGB'
1361-
}.get(im.mode)
1358+
def _supported_modes():
1359+
return ["RGB", "RGBA", "P", "I", "LA", "L", "1"]
13621360

13631361

13641362
# --------------------------------------------------------------------

src/PIL/WebPImagePlugin.py

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -342,17 +342,22 @@ def _save(im, fp, filename):
342342
fp.write(data)
343343

344344

345-
def _convert_mode(im):
346-
mode = im.mode
347-
if mode == 'P':
348-
return 'RGBA' if 'A' in im.im.getpalettemode() else 'RGB'
349-
return {
350-
# Pillow doesn't support L modes for webp for now.
351-
'L':'RGB',
352-
'LA':'RGBA',
353-
'I':'RGB',
354-
'CMYK':'RGB'
355-
}.get(mode)
345+
def _supported_modes():
346+
return [
347+
"RGB",
348+
"RGBA",
349+
"RGBa",
350+
"RGBX",
351+
"CMYK",
352+
"YCbCr",
353+
"HSV",
354+
"I",
355+
"F",
356+
"P",
357+
"LA",
358+
"L",
359+
"1",
360+
]
356361

357362

358363
Image.register_open(WebPImageFile.format, WebPImageFile, _accept)

0 commit comments

Comments
 (0)