Auto-resize large images (>=5MB) in read_image tool

Images >= 5MB are now automatically resized to < 4.9MB using ImageMagick
before being sent to the LLM. This prevents API errors from oversized images.

- Uses iterative quality/scale reduction to find optimal size
- Converts to JPEG for better compression
- Shows original and resized size in terminal output (e.g., '6.2 MB → 4.1 MB (resized)')
- Falls back to original if ImageMagick fails or isn't available
This commit is contained in:
Dhanji R. Prasanna
2026-01-16 21:09:38 +05:30
parent fc702168ab
commit 1003386f7f
2 changed files with 151 additions and 3 deletions

View File

@@ -199,3 +199,32 @@ fn test_image_dimensions_gif() {
assert_eq!(width, 100);
assert_eq!(height, 200);
}
#[test]
fn test_resize_image_if_needed_small_image() {
use g3_core::tools::file_ops::resize_image_if_needed;
use std::path::Path;
// Small image should not be resized
let small_bytes = vec![0u8; 1000]; // 1KB
let path = Path::new("test.jpg");
let target_size = 5 * 1024 * 1024; // 5MB
let result = resize_image_if_needed(&small_bytes, path, target_size).unwrap();
assert_eq!(result.len(), small_bytes.len(), "Small image should not be resized");
}
#[test]
fn test_resize_image_if_needed_returns_original_on_failure() {
use g3_core::tools::file_ops::resize_image_if_needed;
use std::path::Path;
// Invalid image data - ImageMagick will fail, should return original
let invalid_bytes = vec![0u8; 6 * 1024 * 1024]; // 6MB of zeros
let path = Path::new("test.jpg");
let target_size = 5 * 1024 * 1024; // 5MB
let result = resize_image_if_needed(&invalid_bytes, path, target_size).unwrap();
// Should return original since ImageMagick can't process invalid data
assert_eq!(result.len(), invalid_bytes.len(), "Invalid image should return original");
}