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.rs858 chars23 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:
84 chars5 lines
You can then start the Rocket server as follows:
main.rs145 chars7 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