Reputation: 369
I am playing with the youtube api and I would like to download the thumbnails and process them. I've managed to download them in binary doing a simple http request and I can save them as a .jepec file. What I would like to do is not having to save the image as a file and parse the binary directly into an image all in memory to avoid leaving files behind. Any idea on hat do I need to do to accompish this?
Here is my code:
#[tokio::main(flavor = "current_thread")]
async fn main() {
let res = reqwest::get("https://i.ytimg.com/vi/dQw4w9WgXcQ/hqdefault.jpg")
.await
.unwrap();
let bytes: Bytes = res.bytes().await.unwrap();
let _ = fs::write("img.jpeg", bin.clone()); // this saves the image correctly
let img = ????::from(bytes); // help here
}
Upvotes: 1
Views: 1238
Reputation: 2917
You can use the jpeg_decoder
crate:
use jpeg_decoder::Decoder;
let mut decoder = Decoder::new(&*bytes);
let pixels = decoder.decode().expect("jpeg decoding failed");
let info = decoder.info().unwrap(); // image metadata
If you call decode()
from an async
function, you should do so in a blocking task using tokio::spawn_blocking
, as decode()
is not itself async
.
Upvotes: 2