(image_path: Path, max_size_bytes: int = 5 * 1024 * 1024)
| 489 | return False, f"Code execution failed: {str(e)}", None |
| 490 | |
| 491 | def compress_image_if_needed(image_path: Path, max_size_bytes: int = 5 * 1024 * 1024) -> bytes: |
| 492 | |
| 493 | actual_target = int(max_size_bytes * 0.75) |
| 494 | original_size = image_path.stat().st_size |
| 495 | |
| 496 | with Image.open(image_path) as img: |
| 497 | if img.mode != 'RGB': |
| 498 | img = img.convert('RGB') |
| 499 | width, height = img.size |
| 500 | if width > JPEG_MAX_DIMENSION or height > JPEG_MAX_DIMENSION: |
| 501 | logging.warning( |
| 502 | f"Image '{image_path}' has dimensions ({width}x{height}) " |
| 503 | f"exceeding JPEG limit. Resizing it down." |
| 504 | ) |
| 505 | aspect_ratio = width / height |
| 506 | if width > height: |
| 507 | new_width = JPEG_MAX_DIMENSION |
| 508 | new_height = int(new_width / aspect_ratio) |
| 509 | else: |
| 510 | new_height = JPEG_MAX_DIMENSION |
| 511 | new_width = int(new_height * aspect_ratio) |
| 512 | |
| 513 | |
| 514 | img = img.resize((new_width, new_height), Image.Resampling.LANCZOS) |
| 515 | logging.info(f"Resized to ({img.width}x{img.height})") |
| 516 | |
| 517 | |
| 518 | if original_size <= actual_target: |
| 519 | with open(image_path, 'rb') as f: |
| 520 | return f.read() |
| 521 | |
| 522 | |
| 523 | for quality in [85, 75, 65, 55, 45, 35, 25]: |
| 524 | buffer = io.BytesIO() |
| 525 | img.save(buffer, format='JPEG', quality=quality, optimize=True) |
| 526 | compressed_data = buffer.getvalue() |
| 527 | |
| 528 | if len(compressed_data) <= actual_target: |
| 529 | return compressed_data |
| 530 | |
| 531 | |
| 532 | current_width, current_height = img.size |
| 533 | for scale in [0.8, 0.6, 0.4, 0.2]: |
| 534 | new_width = int(current_width * scale) |
| 535 | new_height = int(current_height * scale) |
| 536 | resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS) |
| 537 | |
| 538 | buffer = io.BytesIO() |
| 539 | resized_img.save(buffer, format='JPEG', quality=25, optimize=True) |
| 540 | compressed_data = buffer.getvalue() |
| 541 | |
| 542 | if len(compressed_data) <= actual_target: |
| 543 | return compressed_data |
| 544 | |
| 545 | |
| 546 | buffer = io.BytesIO() |
| 547 | resized_img.save(buffer, format='JPEG', quality=10, optimize=True) |
| 548 | return buffer.getvalue() |
no outgoing calls
no test coverage detected