|
20 | 20 | from django.core.cache import cache |
21 | 21 | from docx.shared import Mm |
22 | 22 | from docxtpl import DocxTemplate, InlineImage, Listing, RichText |
23 | | -from PIL import UnidentifiedImageError |
| 23 | +from PIL import Image as PImage, UnidentifiedImageError |
24 | 24 | from ..models import Attribute, ProjectPhase, ProjectAttributeFile, ProjectPhaseSectionAttribute |
25 | 25 | from ..models.utils import create_identifier |
26 | 26 | from projects.helpers import ( |
@@ -211,6 +211,21 @@ def get_super(_script): |
211 | 211 | return True |
212 | 212 | else: |
213 | 213 | 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 | + |
214 | 229 | def render_template(project, document_template, preview): |
215 | 230 |
|
216 | 231 | def fetch_relevant_attributes(doc): |
@@ -314,19 +329,20 @@ def get_display_and_raw_value(attribute, value, ignore_multiple_choice=False): |
314 | 329 | return (display_list, raw_list, element_data, raw_to_display_mapped) |
315 | 330 |
|
316 | 331 | if attribute.value_type == Attribute.TYPE_IMAGE and value: |
| 332 | + image = validate_image(value) |
317 | 333 | if doc_type == 'docx': |
318 | 334 | try: |
319 | 335 | 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)) |
321 | 337 | 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)) |
323 | 339 | else: |
324 | | - display_value = InlineImage(doc, value, width=Mm(150)) |
| 340 | + display_value = InlineImage(doc, image, width=Mm(150)) |
325 | 341 | except (FileNotFoundError, UnidentifiedImageError): |
326 | 342 | log.error(f'Image not found or is corrupted at {value}') |
327 | 343 | display_value = None |
328 | 344 | else: |
329 | | - display_value = value |
| 345 | + display_value = image |
330 | 346 | else: |
331 | 347 | display_value = attribute.get_attribute_display(value) |
332 | 348 |
|
|
0 commit comments