MCPcopy Create free account
hub / github.com/Speakn0w/RealChart2Code / compress_image_if_needed

Function compress_image_if_needed

RealChart2Code_eval/evaluate_task1.py:459–516  ·  view source on GitHub ↗
(image_path: Path, max_size_bytes: int = 5 * 1024 * 1024)

Source from the content-addressed store, hash-verified

457 return False, f"Code execution failed: {str(e)}", None
458
459def compress_image_if_needed(image_path: Path, max_size_bytes: int = 5 * 1024 * 1024) -> bytes:
460
461 actual_target = int(max_size_bytes * 0.75)
462 original_size = image_path.stat().st_size
463
464 with Image.open(image_path) as img:
465 if img.mode != 'RGB':
466 img = img.convert('RGB')
467 width, height = img.size
468 if width > JPEG_MAX_DIMENSION or height > JPEG_MAX_DIMENSION:
469 logging.warning(
470 f"Image '{image_path}' has dimensions ({width}x{height}) "
471 f"exceeding JPEG limit. Resizing it down."
472 )
473 aspect_ratio = width / height
474 if width > height:
475 new_width = JPEG_MAX_DIMENSION
476 new_height = int(new_width / aspect_ratio)
477 else:
478 new_height = JPEG_MAX_DIMENSION
479 new_width = int(new_height * aspect_ratio)
480
481
482 img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
483 logging.info(f"Resized to ({img.width}x{img.height})")
484
485
486 if original_size <= actual_target:
487 with open(image_path, 'rb') as f:
488 return f.read()
489
490
491 for quality in [85, 75, 65, 55, 45, 35, 25]:
492 buffer = io.BytesIO()
493 img.save(buffer, format='JPEG', quality=quality, optimize=True)
494 compressed_data = buffer.getvalue()
495
496 if len(compressed_data) <= actual_target:
497 return compressed_data
498
499
500 current_width, current_height = img.size
501 for scale in [0.8, 0.6, 0.4, 0.2]:
502 new_width = int(current_width * scale)
503 new_height = int(current_height * scale)
504 resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
505
506 buffer = io.BytesIO()
507 resized_img.save(buffer, format='JPEG', quality=25, optimize=True)
508 compressed_data = buffer.getvalue()
509
510 if len(compressed_data) <= actual_target:
511 return compressed_data
512
513
514 buffer = io.BytesIO()
515 resized_img.save(buffer, format='JPEG', quality=10, optimize=True)
516 return buffer.getvalue()

Callers 1

encode_image_to_base64Function · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected