Spaces:
Sleeping
Sleeping
File size: 7,573 Bytes
343eed9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 | use crate::error::Result;
use image::{DynamicImage, GenericImageView, ImageBuffer, Rgba};
use imageproc::drawing::{draw_text_mut, draw_filled_rect_mut};
use ab_glyph::{FontRef, PxScale};
use std::path::Path;
const FONT_PATH: &str = "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf";
/// Charger une image depuis un fichier
pub fn load_image(path: &Path) -> Result<DynamicImage> {
image::open(path).map_err(|e| {
crate::error::GeneratorError::ImageGenerationFailed(format!("Failed to load image: {}", e))
})
}
/// Sauvegarder une image
pub fn save_image(img: &DynamicImage, path: &Path) -> Result<()> {
img.save(path).map_err(|e| {
crate::error::GeneratorError::ImageGenerationFailed(format!("Failed to save image: {}", e))
})
}
/// Appliquer un overlay de texte sur l'image
pub fn add_text_overlay(img: DynamicImage, title: Option<&str>, subtitle: Option<&str>) -> Result<DynamicImage> {
let mut rgba = img.to_rgba8();
let (w, h) = rgba.dimensions();
let font_data = std::fs::read(FONT_PATH).map_err(|e| {
crate::error::GeneratorError::ImageGenerationFailed(format!("Failed to read font: {}", e))
})?;
let font = FontRef::try_from_slice(&font_data).map_err(|e| {
crate::error::GeneratorError::ImageGenerationFailed(format!("Failed to load font: {}", e))
})?;
// 1. DESSINER LE TITRE
if let Some(t) = title {
if t != "None" && !t.is_empty() {
let scale = PxScale::from(90.0);
let lines = wrap_text(t, 12);
let mut y_text = h as i32 / 5;
for line in lines {
let (tw, _) = get_text_size(&font, scale, &line);
let x = (w as i32 - tw as i32) / 2;
// Outline Rouge Sang
let red = Rgba([150, 0, 0, 255]);
for off_x in [-3, 3] {
for off_y in [-3, 3] {
draw_text_mut(&mut rgba, red, x + off_x, y_text + off_y, scale, &font, &line);
}
}
// Texte Blanc
draw_text_mut(&mut rgba, Rgba([255, 255, 255, 255]), x, y_text, scale, &font, &line);
y_text += 100;
}
}
}
// 2. DESSINER LA NARRATION (Subtitle)
if let Some(s) = subtitle {
if s != "None" && !s.is_empty() {
let scale_sub = PxScale::from(65.0);
let lines = wrap_text(s, 22);
let line_height = 85;
let total_h = lines.len() as i32 * line_height;
let y_start_base = h as i32 - 450;
// Boîte de fond noire
draw_filled_rect_mut(
&mut rgba,
imageproc::rect::Rect::at(50, y_start_base - 20).of_size(w - 100, total_h as u32 + 40),
Rgba([0, 0, 0, 200])
);
let mut y_curr = y_start_base;
for line in lines {
let (tw, _) = get_text_size(&font, scale_sub, &line);
let x = (w as i32 - tw as i32) / 2;
// Contour Rouge
let red_sub = Rgba([200, 0, 0, 255]);
for off_x in [-2, 2] {
for off_y in [-2, 2] {
draw_text_mut(&mut rgba, red_sub, x + off_x, y_curr + off_y, scale_sub, &font, &line);
}
}
// Texte Jaune Karaoké
draw_text_mut(&mut rgba, Rgba([255, 255, 0, 255]), x, y_curr, scale_sub, &font, &line);
y_curr += line_height;
}
}
}
Ok(DynamicImage::ImageRgba8(rgba))
}
fn wrap_text(text: &str, max_chars: usize) -> Vec<String> {
let mut lines = Vec::new();
for paragraph in text.split('\n') {
let words: Vec<&str> = paragraph.split_whitespace().collect();
let mut current_line = String::new();
for word in words {
if current_line.is_empty() {
current_line.push_str(word);
} else if current_line.len() + 1 + word.len() <= max_chars {
current_line.push(' ');
current_line.push_str(word);
} else {
lines.push(current_line);
current_line = String::from(word);
}
}
if !current_line.is_empty() {
lines.push(current_line);
}
}
lines
}
fn get_text_size(_font: &FontRef, scale: PxScale, text: &str) -> (u32, u32) {
let char_width = scale.x * 0.6;
let width = (text.len() as f32 * char_width).ceil() as u32;
let height = scale.y.ceil() as u32;
(width, height)
}
/// Appliquer un overlay de texte sur l'image (compatibilité existante)
pub fn render_text_overlay(img: DynamicImage, text: &str) -> Result<DynamicImage> {
add_text_overlay(img, None, Some(text))
}
/// Redimensionner l'image
pub fn resize(img: DynamicImage, width: u32, height: u32) -> DynamicImage {
img.resize_exact(width, height, image::imageops::FilterType::Lanczos3)
}
/// Appliquer un filtre de saturation
pub fn adjust_saturation(img: DynamicImage, factor: f32) -> Result<DynamicImage> {
let rgba = img.to_rgba8();
let mut output = ImageBuffer::new(rgba.width(), rgba.height());
for (x, y, pixel) in rgba.enumerate_pixels() {
let [r, g, b, a] = pixel.0;
let (h, s, v) = rgb_to_hsv(r, g, b);
let new_s = (s * factor).min(1.0);
let (new_r, new_g, new_b) = hsv_to_rgb(h, new_s, v);
output.put_pixel(x, y, Rgba([new_r, new_g, new_b, a]));
}
Ok(DynamicImage::ImageRgba8(output))
}
/// Convertir RGB en HSV
fn rgb_to_hsv(r: u8, g: u8, b: u8) -> (f32, f32, f32) {
let r = r as f32 / 255.0;
let g = g as f32 / 255.0;
let b = b as f32 / 255.0;
let max = r.max(g).max(b);
let min = r.min(g).min(b);
let delta = max - min;
let h = if delta == 0.0 {
0.0
} else if max == r {
(60.0 * ((g - b) / delta) + 360.0) % 360.0
} else if max == g {
(60.0 * ((b - r) / delta) + 120.0) % 360.0
} else {
(60.0 * ((r - g) / delta) + 240.0) % 360.0
};
let s = if max == 0.0 { 0.0 } else { delta / max };
let v = max;
(h, s, v)
}
/// Convertir HSV en RGB
fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (u8, u8, u8) {
let c = v * s;
let hp = h / 60.0;
let x = c * (1.0 - (hp % 2.0 - 1.0).abs());
let (r1, g1, b1) = match hp as i32 {
0 => (c, x, 0.0),
1 => (x, c, 0.0),
2 => (0.0, c, x),
3 => (0.0, x, c),
4 => (x, 0.0, c),
_ => (c, 0.0, x),
};
let m = v - c;
let r = ((r1 + m) * 255.0) as u8;
let g = ((g1 + m) * 255.0) as u8;
let b = ((b1 + m) * 255.0) as u8;
(r, g, b)
}
/// Extraire les statistiques d'une image
pub fn get_image_stats(img: &DynamicImage) -> ImageStats {
let (width, height) = img.dimensions();
let rgba = img.to_rgba8();
let pixel_count = (width * height) as usize;
let mut r_sum = 0u64;
let mut g_sum = 0u64;
let mut b_sum = 0u64;
for pixel in rgba.pixels() {
r_sum += pixel.0[0] as u64;
g_sum += pixel.0[1] as u64;
b_sum += pixel.0[2] as u64;
}
ImageStats {
width,
height,
avg_red: (r_sum / pixel_count as u64) as u8,
avg_green: (g_sum / pixel_count as u64) as u8,
avg_blue: (b_sum / pixel_count as u64) as u8,
}
}
#[derive(Debug, Clone)]
pub struct ImageStats {
pub width: u32,
pub height: u32,
pub avg_red: u8,
pub avg_green: u8,
pub avg_blue: u8,
}
|