如何在某些网站上检索图像并将其正确地使用Reqwest保存到本地?我尝试使用.text()
并且图片损坏了。
Error interpreting JPEG image file (Not a JPEG file: starts with 0xef 0xbf)
我尝试过的代码
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),
}
}
答案 0 :(得分:5)
请勿使用text
,它是用于文本的,因此会尝试对原始字节进行解码。
只需编写response,它实现Into<Body>
,其中Body
是一个流(比获取字节更有效):
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),
}