Why do the bytes of a PNG image downloaded with reqwest differ from those downloaded with Python?

680 Views Asked by At

I'm trying to use reqwest library to download a PNG file, but when I download it I see a strange behaviour respect other programming languages like: Python.

For instance:

let content = reqwest::get("https://www.google.es/images/searchbox/desktop_searchbox_sprites302_hr.png").await?;

If I print the result as a bytes array (println!("{:?}", content.text().await?.as_bytes());

[ 191, 189, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 40, 0, 0, 0, 82, 8, 3, 0, 0, 0, 17,  191, 189, 102,  191, 189, 0, 0, 0, 108, 80, 76, 84, 69, 0, 0, 0,  191, 189,  191, 189,  191, 189,...]

However, the result using Python requests is:

[137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 40, 0, 0, 0, 82, 8, 3, 0, 0, 0, 17, 153, 102, 248, ...]

In the Rust version, I see a lot of 191, 189. This sequence repeats a lot throughout the array, but in Python doesn't appear at all.

What am I doing wrong in Rust?

1

There are 1 best solutions below

1
On

I see a lot of 191, 189

It's better seen as EF, BF, BD, which is the Unicode replacement character encoded as UTF-8. Binary data is not text data. You should not use text for binary data, instead use bytes.

const URL: &str = "https://www.google.es/images/searchbox/desktop_searchbox_sprites302_hr.png";

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let content = reqwest::get(URL).await?;
    let bytes = content.bytes().await?;
    println!("{:x?}", &bytes[..]);

    Ok(())
}
[89, 50, 4e, 47, d, a, 1a, a, 0, 0, 0, d, 49, 48, 44, 52, 0, 0, 0, 28, 0, 0, 0, 52, 8, 3, 0, 0, 0, 11, 99, 66, f8, 0, 0, 0, 6c, 50, 4c, 54, 45, 0, 0, 0, 9f, ...