1

How do I retrieve an image on some website and save it to local using Reqwest correctly? I have tried to use .text() and the image are broken.

Error interpreting JPEG image file (Not a JPEG file: starts with 0xef 0xbf)

The code that I have tried

extern crate reqwest;

use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;

fn main() {
    let mut image_file = reqwest::Client::new()
        .get("https://images.pexels.com/photos/2124773/pexels-photo-2124773.jpeg")
        .send()
        .unwrap()
        .text()
        .unwrap();
    let path = Path::new("tmp/img_test.jpeg");
    let display = path.display();
    let mut file = match File::create(&path) {
        Err(why) => panic!("couldn't create {}: {}", display, why.description()),
        Ok(file) => file,
    };
    match file.write_all(image_file.as_bytes()) {
        Err(why) => panic!("couldn't write to {}: {}", display, why.description()),
        Ok(_) => println!("successfully wrote to {}", display),
    }
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Andra
  • 1,282
  • 2
  • 11
  • 34

1 Answers1

8

Don't use text, which is for text and thus tries to decode the raw bytes.

Just write the response, which implements Into<Body> where Body is a stream (which is also more efficient than getting the bytes):

let mut client = reqwest::Client::new();
let mut image_file = client
    .get("https://images.pexels.com/photos/2124773/pexels-photo-2124773.jpeg")
    .send()
    .unwrap();

let path = Path::new("img_test.jpeg");
let display = path.display();
let mut file = match File::create(&path) {
    Err(why) => panic!("couldn't create {}: {}", display, why.description()),
    Ok(file) => file,
};
match std::io::copy(&mut image_file, &mut file) {
    Err(why) => panic!("couldn't write to {}: {}", display, why.description()),
    Ok(_) => println!("successfully wrote to {}", display),
}
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758