Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
Discussion options

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.

You must be logged in to vote

Use the write_to method:

let mut bytes: Vec<u8> = Vec::new();
img.write_to(&mut Cursor::new(&mut bytes), image::ImageOutputFormat::Png)?;

Replies: 1 comment

Comment options

Use the write_to method:

let mut bytes: Vec<u8> = Vec::new();
img.write_to(&mut Cursor::new(&mut bytes), image::ImageOutputFormat::Png)?;
You must be logged in to vote
0 replies
Answer selected by kartikynwa
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
🙏
Q&A
Labels
None yet
2 participants
Morty Proxy This is a proxified and sanitized view of the page, visit original site.