gpt4 book ai didi

rust - 为什么使用 Reqwest 的 .text() 方法下载的图像会损坏?

转载 作者:行者123 更新时间:2023-11-29 08:22:38 27 4
gpt4 key购买 nike

如何使用 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),
}
}

最佳答案

不要使用 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),
}

关于rust - 为什么使用 Reqwest 的 .text() 方法下载的图像会损坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56019047/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com