How to send a resized image the body for a response for actix-web? #1966
Answered
by
fintelia
kartikynwa
asked this question in
Q&A
-
First time working with images so I am a bit confused. This is the code that I have: #[get("/sprite/{sprite_id}.png")]
pub async fn get_sprite(
data: web::Data<AppState>,
path: web::Path<(i64,)>,
) -> impl Responder {
let (sprite_id,) = path.into_inner();
let result = sqlx::query!("SELECT filepath FROM sprites WHERE id=?", sprite_id)
.fetch_one(&data.db)
.await;
let sprite_path: PathBuf = if let Ok(row) = result {
row.filepath.into()
} else {
return HttpResponse::NotFound().body("Inexistent sprite id");
};
let img = ImageReader::open(sprite_path)
.unwrap()
.decode()
.unwrap()
.resize(256, 256, image::imageops::FilterType::Triangle);
HttpResponse::Ok()
.insert_header(("content-type", "image/png"))
.body(img.as_bytes().to_vec())
} This compiles and runs but the response body is not a valid PNG file. I guess this because it is a decoded image and I have to encode it to a PNG before sending it but I cannot figure out how to. Any advice? Thanks. |
Beta Was this translation helpful? Give feedback.
Answered by
fintelia
Jul 22, 2023
Replies: 1 comment
-
Use the let mut bytes: Vec<u8> = Vec::new();
img.write_to(&mut Cursor::new(&mut bytes), image::ImageOutputFormat::Png)?; |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
kartikynwa
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use the
write_to
method: