resize an image based on a url query and return the image in rust

To resize an image based on a URL query and return the resulting image in Rust, you can use the image and rocket crates.

Here is an example code snippet:

main.rs
use std::io::Cursor;
use rocket::http::ContentType;
use rocket::http::RawStr;
use rocket::response::Response;
use rocket::response::NamedFile;
use rocket_contrib::serve::StaticFiles;
use image::{GenericImageView, ImageFormat};

#[get("/image?<url>&<size>")]
fn image(url: &RawStr, size: &RawStr) -> Response<'static> {
    let img_result = image::open(&url).unwrap();
    let dimensions = size.as_str().split('x').collect::<Vec<_>>();
    let width = dimensions[0].parse().unwrap();
    let height = dimensions[1].parse().unwrap();
    let resized = img_result.resize_exact(width, height, image::imageops::FilterType::Lanczos3);
    let mut buffer = Cursor::new(Vec::new());
    resized.write_to(&mut buffer, ImageFormat::JPEG).unwrap();
    Response::build()
        .header(ContentType::JPEG)
        .sized_body(buffer.into_inner())
        .finalize()
}
858 chars
23 lines

In this code, we define a GET endpoint /image that takes two query parameters: url and size. The size parameter represents the new dimensions of the image, and is expected to be in the format widthxheight (e.g. 400x300).

We use the image crate to load the image from the given URL, and resize it using the desired dimensions. We then write the result to a buffer and return the buffer as the response. The response is automatically set to Content-Type: image/jpeg.

Note that this code can handle errors better, for example by returning proper error messages when the query parameters are not in the expected format, or when the image cannot be loaded from the given URL.

To run this code, you will need to add the following dependencies to your Cargo.toml file:

[dependencies]
rocket = "0.5.0-rc.1"
rocket_contrib = "0.5.0-rc.1"
image = "0.23.1"
84 chars
5 lines

You can then start the Rocket server as follows:

main.rs
fn main() {
    rocket::ignite()
        .mount("/", routes![image])
        .mount("/static", StaticFiles::from("static"))
        .launch();
}
145 chars
7 lines

This code serves images dynamically, and that may have some performance impact on the server if the requests are continuous. It's recommended to use a proxy server/cache system in front of your app to reduce the load.

gistlibby LogSnag