This commit is contained in:
parent
b62b01190e
commit
2aca57c86a
|
@ -1,6 +1,7 @@
|
|||
use actix_web::error::ErrorInternalServerError;
|
||||
use image::{imageops::FilterType, DynamicImage};
|
||||
use std::{collections::HashMap, io::Cursor};
|
||||
use image::guess_format;
|
||||
|
||||
pub const THUMB_WIDTHS: [u32; 7] = [10, 40, 110, 300, 600, 800, 1400];
|
||||
|
||||
|
@ -69,26 +70,19 @@ pub fn parse_file_path(requested_path: &str) -> (String, u32, String) {
|
|||
(base_filename, width, extension)
|
||||
}
|
||||
|
||||
/// Выбирает ближайший подходящий размер из предопределённых.
|
||||
pub fn find_closest_width(requested_width: u32) -> u32 {
|
||||
*THUMB_WIDTHS
|
||||
.iter()
|
||||
.min_by_key(|&&width| (width as i32 - requested_width as i32).abs())
|
||||
.unwrap_or(&THUMB_WIDTHS[0]) // Возвращаем самый маленький размер, если ничего не подошло
|
||||
}
|
||||
|
||||
/// Генерирует миниатюры изображения.
|
||||
pub async fn generate_thumbnails(image: &DynamicImage) -> Result<HashMap<u32, Vec<u8>>, actix_web::Error> {
|
||||
let mut thumbnails = HashMap::new();
|
||||
|
||||
let format = guess_format(&image.as_bytes()).unwrap();
|
||||
for &width in THUMB_WIDTHS.iter().filter(|&&w| w < image.width()) {
|
||||
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
|
||||
.write_to(&mut Cursor::new(&mut buffer), format)
|
||||
.map_err(|_| ErrorInternalServerError("Не удалось сгенерировать миниатюру"))?; // Сохранение изображения в указанном формате
|
||||
thumbnails.insert(width, buffer);
|
||||
}
|
||||
|
||||
Ok(thumbnails)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user