Skip to main content

vtcode_core/utils/
image_processing.rs

1//! Image processing utilities
2//!
3//! Re-exports from `vtcode-commons::image` plus URL-based image fetching.
4
5use anyhow::{Context, Result};
6pub use vtcode_commons::image::*;
7
8/// Reads an image from a URL and converts it to base64 format
9pub async fn read_image_from_url(url: &str) -> Result<ImageData> {
10    if !url.starts_with("http://") && !url.starts_with("https://") {
11        return Err(anyhow::anyhow!("Invalid URL: {url}"));
12    }
13
14    let client = vtcode_commons::http::apply_connect_timeout(
15        reqwest::Client::builder().timeout(std::time::Duration::from_secs(30)),
16    )
17    .build()
18    .context("Failed to create HTTP client")?;
19
20    let response = client
21        .get(url)
22        .send()
23        .await
24        .with_context(|| format!("Failed to fetch image from URL: {url}"))?;
25
26    if !response.status().is_success() {
27        return Err(anyhow::anyhow!("HTTP error when fetching image: {} (status: {})", url, response.status()));
28    }
29
30    let content_length = response.content_length().unwrap_or(0);
31    if content_length > 20 * 1024 * 1024 {
32        return Err(anyhow::anyhow!("Image from URL too large: {content_length} bytes (max 20MB)"));
33    }
34
35    let declared_mime_type = response
36        .headers()
37        .get(reqwest::header::CONTENT_TYPE)
38        .and_then(|v| v.to_str().ok())
39        .and_then(detect_mime_type_from_content_type);
40
41    // A declared but unsupported image type (SVG/BMP/TIFF) must fail here
42    // instead of falling through to magic-byte sniffing, which would
43    // mislabel SVG markup as PNG and produce a provider 400 downstream.
44    if let Some(content_type) = response
45        .headers()
46        .get(reqwest::header::CONTENT_TYPE)
47        .and_then(|v| v.to_str().ok())
48        && content_type.to_lowercase().starts_with("image/")
49        && declared_mime_type
50            .as_deref()
51            .is_none_or(|mime| !is_supported_image_mime_type(mime))
52    {
53        return Err(anyhow::anyhow!("Unsupported image content type for LLM vision: {content_type}"));
54    }
55
56    let mime_type = declared_mime_type;
57
58    let file_contents = response
59        .bytes()
60        .await
61        .with_context(|| format!("Failed to read response body from: {url}"))?
62        .to_vec();
63
64    // Reject markup/error pages that slipped past the header check: SVG and
65    // HTML payloads are text, not raster images, and providers refuse them.
66    let leading = file_contents.iter().take_while(|byte| byte.is_ascii_whitespace()).count();
67    if file_contents.len() > leading && file_contents[leading] == b'<' {
68        return Err(anyhow::anyhow!("URL did not return raster image data: {url}"));
69    }
70
71    let mime_type = mime_type.unwrap_or_else(|| detect_mime_type_from_data(&file_contents));
72    if !is_supported_image_mime_type(&mime_type) {
73        return Err(anyhow::anyhow!("Unsupported image content type for LLM vision: {mime_type}"));
74    }
75    let base64_data = encode_to_base64(&file_contents);
76
77    Ok(ImageData {
78        base64_data,
79        mime_type,
80        file_path: url.to_string(),
81        size: file_contents.len() as u64,
82    })
83}