Skip to content

Commit 1fff671

Browse files
committed
Added convert_mode param when saving
1 parent e634c4d commit 1fff671

11 files changed

Lines changed: 128 additions & 8 deletions

Tests/images/pil123rgba_red.jpg

4.56 KB
Loading

Tests/test_file_gif.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -785,6 +785,17 @@ def test_save_I(tmp_path):
785785
assert_image_equal(reloaded.convert("L"), im.convert("L"))
786786

787787

788+
def test_save_wrong_modes(self):
789+
out = BytesIO()
790+
for mode in ["CMYK"]:
791+
img = Image.new(mode, (20, 20))
792+
self.assertRaises(ValueError, img.save, out, "GIF")
793+
794+
for mode in ["CMYK", "LA"]:
795+
img = Image.new(mode, (20, 20))
796+
img.save(out, "GIF", convert_mode=True)
797+
798+
788799
def test_getdata():
789800
# Test getheader/getdata against legacy values.
790801
# Create a 'P' image with holes in the palette.

Tests/test_file_jpeg.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -547,14 +547,26 @@ def test_save_correct_modes(self):
547547
img = Image.new(mode, (20, 20))
548548
img.save(out, "JPEG")
549549

550-
def test_save_wrong_modes(self):
550+
def test_save_wrong_modes(self, tmp_path):
551551
# ref https://github.com/python-pillow/Pillow/issues/2005
552552
out = BytesIO()
553-
for mode in ["LA", "La", "RGBA", "RGBa", "P"]:
553+
for mode in ["LA", "La", "RGBA", "RGBa", "P", "I"]:
554554
img = Image.new(mode, (20, 20))
555555
with pytest.raises(IOError):
556556
img.save(out, "JPEG")
557557

558+
for mode in ["LA", "RGBA", "P", "I"]:
559+
img = Image.new(mode, (20, 20))
560+
img.save(out, "JPEG", convert_mode=True)
561+
562+
temp_file = str(tmp_path / "temp.jpg")
563+
with Image.open("Tests/images/pil123rgba.png") as img:
564+
img.save(temp_file, convert_mode=True, fill_color="red")
565+
566+
with Image.open(temp_file) as reloaded:
567+
with Image.open("Tests/images/pil123rgba_red.jpg") as target:
568+
assert_image_similar(reloaded, target, 4)
569+
558570
def test_save_tiff_with_dpi(self, tmp_path):
559571
# Arrange
560572
outfile = str(tmp_path / "temp.tif")

Tests/test_file_png.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,14 @@ def test_load_transparent_rgb(self):
230230
# image has 876 transparent pixels
231231
assert im.getchannel("A").getcolors()[0][0] == 876
232232

233+
def test_save_CMYK(self):
234+
out = BytesIO()
235+
im = Image.new("CMYK", (20, 20))
236+
with pytest.raises(IOError):
237+
im.save(out, "PNG")
238+
239+
im.save(out, "PNG", convert_mode=True)
240+
233241
def test_save_p_transparent_palette(self, tmp_path):
234242
in_file = "Tests/images/pil123p.png"
235243
with Image.open(in_file) as im:

Tests/test_file_webp.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
skip_unless_feature,
99
)
1010

11+
from io import BytesIO
12+
1113
try:
1214
from PIL import _webp
1315

@@ -54,6 +56,12 @@ def test_read_rgb(self):
5456
# dwebp -ppm ../../Tests/images/hopper.webp -o hopper_webp_bits.ppm
5557
assert_image_similar_tofile(image, "Tests/images/hopper_webp_bits.ppm", 1.0)
5658

59+
def test_save_convert_mode(self):
60+
out = BytesIO()
61+
for mode in ["CMYK", "I", "L", "LA", "P"]:
62+
img = Image.new(mode, (20, 20))
63+
img.save(out, "WEBP", convert_mode=True)
64+
5765
def test_write_rgb(self, tmp_path):
5866
"""
5967
Can we write a RGB mode file to webp without error.

Tests/test_image.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
import PIL
77
import pytest
8-
from PIL import Image, ImageDraw, ImagePalette, UnidentifiedImageError
8+
from PIL import Image, ImageDraw, ImagePalette, TiffImagePlugin, UnidentifiedImageError
99

1010
from .helper import (
1111
assert_image_equal,
@@ -375,6 +375,14 @@ def test_registered_extensions(self):
375375
for ext in [".cur", ".icns", ".tif", ".tiff"]:
376376
assert ext in extensions
377377

378+
def test_no_convert_mode(self):
379+
self.assertTrue(not hasattr(TiffImagePlugin, "_convert_mode"))
380+
381+
temp_file = self.tempfile("temp.tiff")
382+
383+
im = hopper()
384+
im.save(temp_file, convert_mode=True)
385+
378386
def test_effect_mandelbrot(self):
379387
# Arrange
380388
size = (512, 512)

src/PIL/GifImagePlugin.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -869,6 +869,13 @@ def write(self, data):
869869
return fp.data
870870

871871

872+
def _convert_mode(im):
873+
return {
874+
'LA':'P',
875+
'CMYK':'RGB'
876+
}.get(im.mode)
877+
878+
872879
# --------------------------------------------------------------------
873880
# Registry
874881

src/PIL/Image.py

Lines changed: 41 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2099,10 +2099,6 @@ def save(self, fp, format=None, **params):
20992099
# may mutate self!
21002100
self._ensure_mutable()
21012101

2102-
save_all = params.pop("save_all", False)
2103-
self.encoderinfo = params
2104-
self.encoderconfig = ()
2105-
21062102
preinit()
21072103

21082104
ext = os.path.splitext(filename)[1].lower()
@@ -2117,11 +2113,20 @@ def save(self, fp, format=None, **params):
21172113

21182114
if format.upper() not in SAVE:
21192115
init()
2120-
if save_all:
2116+
if params.pop('save_all', False):
21212117
save_handler = SAVE_ALL[format.upper()]
21222118
else:
21232119
save_handler = SAVE[format.upper()]
21242120

2121+
if params.get('convert_mode'):
2122+
plugin = sys.modules[save_handler.__module__]
2123+
converted_im = self._convert_mode(plugin, params)
2124+
if converted_im:
2125+
return converted_im.save(fp, format, **params)
2126+
2127+
self.encoderinfo = params
2128+
self.encoderconfig = ()
2129+
21252130
if open_fp:
21262131
if params.get("append", False):
21272132
# Open also for reading ("+"), because TIFF save_all
@@ -2137,6 +2142,37 @@ def save(self, fp, format=None, **params):
21372142
if open_fp:
21382143
fp.close()
21392144

2145+
def _convert_mode(self, plugin, params):
2146+
if not hasattr(plugin, '_convert_mode'):
2147+
return
2148+
new_mode = plugin._convert_mode(self)
2149+
if self.mode == 'LA' and new_mode == 'P':
2150+
alpha = self.getchannel('A')
2151+
# Convert the image into P mode but only use 255 colors
2152+
# in the palette out of 256.
2153+
im = self.convert('L') \
2154+
.convert('P', palette=ADAPTIVE, colors=255)
2155+
# Set all pixel values below 128 to 255, and the rest to 0.
2156+
mask = eval(alpha, lambda px: 255 if px < 128 else 0)
2157+
# Paste the color of index 255 and use alpha as a mask.
2158+
im.paste(255, mask)
2159+
# The transparency index is 255.
2160+
im.info['transparency'] = 255
2161+
return im
2162+
2163+
elif self.mode == 'I':
2164+
im = self.point([i//256 for i in range(65536)], 'L')
2165+
return im.convert(new_mode) if new_mode != 'L' else im
2166+
2167+
elif self.mode in ('RGBA', 'LA') and new_mode in ('RGB', 'L'):
2168+
fill_color = params.get('fill_color', 'white')
2169+
background = new(new_mode, self.size, fill_color)
2170+
background.paste(self, self.getchannel('A'))
2171+
return background
2172+
2173+
elif new_mode:
2174+
return self.convert(new_mode)
2175+
21402176
def seek(self, frame):
21412177
"""
21422178
Seeks to the given frame in this sequence file. If you seek

src/PIL/JpegImagePlugin.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -796,6 +796,17 @@ def jpeg_factory(fp=None, filename=None):
796796
return im
797797

798798

799+
def _convert_mode(im):
800+
mode = im.mode
801+
if mode == 'P':
802+
return 'RGBA' if 'A' in im.im.getpalettemode() else 'RGB'
803+
return {
804+
'RGBA':'RGB',
805+
'LA':'L',
806+
'I':'L'
807+
}.get(mode)
808+
809+
799810
# ---------------------------------------------------------------------
800811
# Registry stuff
801812

src/PIL/PngImagePlugin.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1328,6 +1328,12 @@ def append(fp, cid, *data):
13281328
return fp.data
13291329

13301330

1331+
def _convert_mode(im):
1332+
return {
1333+
'CMYK':'RGB'
1334+
}.get(im.mode)
1335+
1336+
13311337
# --------------------------------------------------------------------
13321338
# Registry
13331339

0 commit comments

Comments
 (0)