Skip to content

Do not attempt normalization if mode is already normal#6644

Merged
hugovk merged 1 commit intopython-pillow:mainfrom
radarhere:convert
Oct 19, 2022
Merged

Do not attempt normalization if mode is already normal#6644
hugovk merged 1 commit intopython-pillow:mainfrom
radarhere:convert

Conversation

@radarhere
Copy link
Copy Markdown
Member

While investigating #6643, I found that

>>> from PIL import Image
>>> Image.new("RGB", (1, 1)).convert("XYZ")
Traceback (most recent call last):
  File "PIL/Image.py", line 1035, in convert
ValueError: conversion from RGB to XYZ not supported

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "PIL/Image.py", line 1040, in convert
ValueError: conversion from RGB to XYZ not supported
>>> 

It looks odd that "ValueError: conversion from RGB to XYZ not supported" is raised twice. One would expect the first time to be enough.

This is because of the following code. The intention is that if A -> B isn't supported, then maybe A -> C -> B will work, using the base mode as the intermediary.

Pillow/src/PIL/Image.py

Lines 1034 to 1040 in 243402e

try:
im = self.im.convert(mode, dither)
except ValueError:
try:
# normalize source image and try again
im = self.im.convert(getmodebase(self.mode))
im = im.convert(mode, dither)

But in this case, since getmodebase(self.mode) doesn't change the mode, it becomes A -> A -> B, and fails with the same error again.

This PR modifies that code so that if getmodebase(self.mode) doesn't change the mode, then this alternative conversion path is not attempted.

@radarhere radarhere changed the title Do not attempt normalization if image is already normal Do not attempt normalization if mode is already normal Oct 7, 2022
@hugovk hugovk merged commit 87a9d71 into python-pillow:main Oct 19, 2022
@radarhere radarhere deleted the convert branch October 19, 2022 08:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants