quoter/src/thumbnail.rs

72 lines
3.3 KiB
Rust
Raw Normal View History

2024-08-31 00:32:37 +00:00
use actix_web::error::ErrorInternalServerError;
use image::{imageops::FilterType, DynamicImage};
2024-10-23 09:34:34 +00:00
use std::{cmp::max, collections::HashMap, io::Cursor};
2024-08-31 00:32:37 +00:00
2024-10-23 09:34:34 +00:00
pub const THUMB_WIDTHS: [u32; 7] = [10, 40, 110, 300, 600, 800, 1400];
2024-08-31 00:32:37 +00:00
/// Парсит запрос на миниатюру, извлекая оригинальное имя файла и требуемую ширину.
2024-10-23 10:31:05 +00:00
/// Пример: "filename_150.ext" -> ("filename.ext", 150, "ext")
/// unsafe/1440x/production/image/439efaa0-816f-11ef-b201-439da98539bc.jpg -> ("439efaa0-816f-11ef-b201-439da98539bc.jpg", 1440, "jpg")
/// unsafe/production/image/5627e002-0c53-11ee-9565-0242ac110006.png -> ("5627e002-0c53-11ee-9565-0242ac110006.png", 0, "png")
pub fn parse_image_request(path: &str) -> (String, u32, String) {
2024-10-23 09:34:34 +00:00
let mut path_parts = path.rsplit('/').collect::<Vec<&str>>();
2024-10-23 10:31:05 +00:00
let filename_part = path_parts.pop().unwrap_or("");
let mut width = 0;
if path.starts_with("unsafe") {
if let Some(old_width_str) = path_parts.get(1) {
2024-10-23 09:34:34 +00:00
let mut old_width_str = old_width_str.to_string();
if old_width_str.ends_with('x') {
old_width_str.pop();
2024-10-23 10:31:05 +00:00
if let Ok(w) = old_width_str.parse::<u32>() {
width = w;
2024-10-23 09:34:34 +00:00
}
2024-08-31 00:32:37 +00:00
}
}
2024-10-23 10:31:05 +00:00
}
if let Some((name_part, ext_part)) = filename_part.rsplit_once('.') {
if let Some((base_name, width_str)) = name_part.rsplit_once('_') {
if let Ok(w) = width_str.parse::<u32>() {
return (
format!("{}.{}", base_name, ext_part),
max(w, width),
ext_part.to_string(),
);
2024-10-23 09:34:34 +00:00
}
}
2024-10-23 10:31:05 +00:00
(
format!("{}.{}", name_part, ext_part),
width,
ext_part.to_string().to_lowercase(),
)
} else {
// Если расширение отсутствует, возвращаем имя файла как есть, ширину 0 и пустую строку для расширения
(filename_part.to_string(), width, "".to_string())
2024-08-31 00:32:37 +00:00
}
}
/// Выбирает ближайший подходящий размер из предопределённых.
pub fn find_closest_width(requested_width: u32) -> u32 {
2024-10-22 06:38:30 +00:00
*THUMB_WIDTHS
2024-08-31 00:32:37 +00:00
.iter()
.min_by_key(|&&width| (width as i32 - requested_width as i32).abs())
2024-10-22 06:38:30 +00:00
.unwrap_or(&THUMB_WIDTHS[0]) // Возвращаем самый маленький размер, если ничего не подошло
2024-08-31 00:32:37 +00:00
}
2024-10-22 11:28:54 +00:00
/// Генерирует миниатюры изображения.
2024-10-22 06:38:30 +00:00
pub async fn generate_thumbnails(image: &DynamicImage) -> Result<HashMap<u32, Vec<u8>>, actix_web::Error> {
2024-08-31 00:32:37 +00:00
let mut thumbnails = HashMap::new();
2024-10-23 09:34:34 +00:00
for &width in THUMB_WIDTHS.iter().filter(|&&w| w < image.width()) {
2024-08-31 00:32:37 +00:00
let thumbnail = image.resize(width, u32::MAX, FilterType::Lanczos3); // Ресайз изображения по ширине
let mut buffer = Vec::new();
thumbnail
.write_to(&mut Cursor::new(&mut buffer), image::ImageFormat::Jpeg)
.map_err(|_| ErrorInternalServerError("Failed to generate thumbnail"))?; // Сохранение изображения в формате JPEG
thumbnails.insert(width, buffer);
}
Ok(thumbnails)
}