Skip to content

Commit bc2ba5b

Browse files
author
HenryVisuri
committed
Convert images with CMYK profile to RGB during document export
1 parent 32334e9 commit bc2ba5b

File tree

1 file changed

+21
-5
lines changed

1 file changed

+21
-5
lines changed

projects/exporting/document.py

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
from django.core.cache import cache
2121
from docx.shared import Mm
2222
from docxtpl import DocxTemplate, InlineImage, Listing, RichText
23-
from PIL import UnidentifiedImageError
23+
from PIL import Image as PImage, UnidentifiedImageError
2424
from ..models import Attribute, ProjectPhase, ProjectAttributeFile, ProjectPhaseSectionAttribute
2525
from ..models.utils import create_identifier
2626
from projects.helpers import (
@@ -211,6 +211,21 @@ def get_super(_script):
211211
return True
212212
else:
213213
return False
214+
215+
216+
def validate_image(value):
217+
try:
218+
with PImage.open(value) as image:
219+
if image.format == "JPEG" and image.mode == "CMYK":
220+
log.info(f"Converting CMYK image to RGB: {value}")
221+
image = image.convert("RGB")
222+
image.save(value)
223+
return value
224+
except Exception as exc:
225+
log.error(f"Error validating image: {value}", exc)
226+
return None
227+
228+
214229
def render_template(project, document_template, preview):
215230

216231
def fetch_relevant_attributes(doc):
@@ -314,19 +329,20 @@ def get_display_and_raw_value(attribute, value, ignore_multiple_choice=False):
314329
return (display_list, raw_list, element_data, raw_to_display_mapped)
315330

316331
if attribute.value_type == Attribute.TYPE_IMAGE and value:
332+
image = validate_image(value)
317333
if doc_type == 'docx':
318334
try:
319335
if "kansikuva" in attribute.identifier:
320-
display_value = InlineImage(doc, value, width=Mm(212), height=Mm(172))
336+
display_value = InlineImage(doc, image, width=Mm(212), height=Mm(172))
321337
elif attribute.identifier in ["sijaintikartta", "kaavakartta_a4", "havainnekuva", "kuvaliite_suojelukohteet", "ilmakuva"]:
322-
display_value = InlineImage(doc, value, width=Mm(170))
338+
display_value = InlineImage(doc, image, width=Mm(170))
323339
else:
324-
display_value = InlineImage(doc, value, width=Mm(150))
340+
display_value = InlineImage(doc, image, width=Mm(150))
325341
except (FileNotFoundError, UnidentifiedImageError):
326342
log.error(f'Image not found or is corrupted at {value}')
327343
display_value = None
328344
else:
329-
display_value = value
345+
display_value = image
330346
else:
331347
display_value = attribute.get_attribute_display(value)
332348

0 commit comments

Comments
 (0)