zero4rs 2.0.0

zero4rs is a powerful, pragmatic, and extremely fast web framework for Rust
Documentation
use crate::prelude2::*;

use image::DynamicImage;
use std::io::Cursor;

// 旋转图片
// /x-image/300x300/r12/maps/car_black.png
// 300x300/r12/maps/car_black.png
pub async fn rotate90(request: HttpRequest) -> impl Responder {
    let mut path = request.match_info().get("tail").unwrap();

    let mut _size: &str = "";
    let mut _rotate: &str = "";
    let mut img_path: Option<&str> = None;

    if let Some(i) = path.find('/') {
        _size = &path[0..i];

        if let Some(j) = path[i + 1..].find('/') {
            _rotate = &(&path[i + 1..])[0..j];
            path = &(path[i + 2 + j..]);

            img_path = Some(path);
        }
    }

    if let Some(path) = img_path {
        let file = crate::commons::service_home();

        let image_file = std::path::Path::new(&file)
            .join("RichMedias")
            .join(path)
            .display()
            .to_string();

        let img = image::open(image_file).expect("Failed to open image");

        let rotate_fn = |img: &DynamicImage, angle: &str| {
            match angle {
                "r90" => img.rotate90(),
                "r180" => img.rotate180(),
                "r270" => img.rotate270(),
                _ => img.clone(), // 如果角度不是90, 180, 或270度,返回原图像
            }
        };

        let rotated_img = rotate_fn(&img, _rotate);

        // Encode the image buffer to PNG format
        let mut buffer = Cursor::new(Vec::new());

        // rotated_img.flipv(); // 上下反转
        // rotated_img.fliph(); // 左右反转

        match rotated_img.write_to(&mut buffer, image::ImageFormat::Png) {
            Ok(_) => {
                let bytes = buffer.into_inner();
                HttpResponse::Ok().content_type("image/png").body(bytes)
            }
            Err(e) => {
                // eprintln!("Failed to write image: {}", e);
                HttpResponse::InternalServerError().body(e.to_string())
            }
        }
    } else {
        HttpResponse::InternalServerError().body("Failed to generate image")
    }
}