Add a test for srgbify’ing images with a CMYK profile
- ID
39c4c42- date
2024-04-10 23:04:09+00:00- author
Alex Chan <alex@alexwlchan.net>- parent
f53b4c2- message
Add a test for srgbify'ing images with a CMYK profile- changed files
3 files, 23 additions, 5 deletions
Changed files
images/examples/the-design-of-everyday-things.jpg (0) → images/examples/the-design-of-everyday-things.jpg (954637)
diff --git a/images/examples/the-design-of-everyday-things.jpg b/images/examples/the-design-of-everyday-things.jpg
new file mode 100644
index 0000000..f9527ee
Binary files /dev/null and b/images/examples/the-design-of-everyday-things.jpg differ
images/srgbify.py (2475) → images/srgbify.py (2777)
diff --git a/images/srgbify.py b/images/srgbify.py
index 08f164c..2396485 100755
--- a/images/srgbify.py
+++ b/images/srgbify.py
@@ -27,6 +27,12 @@ from pillow_heif import register_heif_opener
register_heif_opener()
+def get_profile_description(icc_profile):
+ f = io.BytesIO(icc_profile)
+ prf = ImageCms.ImageCmsProfile(f)
+ return prf.profile.profile_description
+
+
def convert_image_to_srgb(im: Image) -> typing.Union[Image, None]:
"""
Convert an image to sRGB and return a new Image instance.
@@ -55,11 +61,12 @@ def convert_image_to_srgb(im: Image) -> typing.Union[Image, None]:
outputProfile=ImageCms.createProfile("sRGB"),
)
except PyCMSError as err:
- if (
- im.mode == "L"
- and b"GRAYXYZ" in icc_profile
- and err.args[0].args == ("cannot build transform",)
- ):
+ profile_name = get_profile_description(icc_profile)
+
+ is_gray_xyz = im.mode == "L" and b"GRAYXYZ" in icc_profile
+ is_cmyk = im.mode == "CMYK" and profile_name == "U.S. Web Coated (SWOP) v2"
+
+ if err.args[0].args == ("cannot build transform",) and (is_gray_xyz or is_cmyk):
return ImageCms.profileToProfile(
im,
inputProfile=io.BytesIO(icc_profile),
images/test_srgbify.py (2378) → images/test_srgbify.py (2665)
diff --git a/images/test_srgbify.py b/images/test_srgbify.py
index a4172d2..790ec75 100644
--- a/images/test_srgbify.py
+++ b/images/test_srgbify.py
@@ -82,3 +82,14 @@ def test_it_preserves_rotation_from_exif_orientation(tmp_path: pathlib.Path):
new_im = convert_image_to_srgb(im)
assert new_im.size == (3024, 4032)
+
+
+def test_it_converts_images_with_a_cmyk_profile():
+ """
+ If an image has a CMYK colour profile, that gets converted to sRGB.
+ """
+ im = Image.open("images/examples/the-design-of-everyday-things.jpg")
+
+ new_im = convert_image_to_srgb(im)
+
+ assert new_im.mode == "RGB"