1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
use std::fs::File;
use std::io::Write;
use http_req::request;
const BING_HOMEPAGE: &str = "http://cn.bing.com";
const IMAGE_JSON_PATH: &str = "http://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1";
pub fn get_bing_image(path: String) {
let url = get_image_url();
println!("图片地址:{}", get_image_url());
let data = get_image_data(url);
println!("字节数:{}", data.len());
println!("文件保存路径:{}", path);
save_as_file(data, path);
println!("成功!");
}
fn get_image_url() -> String {
let mut writer = Vec::new();
request::get(IMAGE_JSON_PATH, &mut writer).expect("【获取图片地址】发送请求失败");
let a1 = String::from_utf8(writer).expect("【获取图片地址】响应处理失败");
let a2 = a1.find("url").expect("【获取图片地址】字符串A查找失败");
let a3 = a1.find("urlbase").expect("【获取图片地址】字符串B查找失败");
let a4 = &a1[a2 + 6..a3 - 3];
BING_HOMEPAGE.to_string() + a4
}
fn get_image_data(url: String) -> Vec<u8> {
let mut writer = Vec::new();
request::get(url, &mut writer).expect("【获取图片数据】发送请求失败");
writer
}
fn save_as_file(data: Vec<u8>, path: String) {
let mut file = File::create(path).expect("【写入文件】创建文件失败");
file.write_all(&data).expect("【写入文件】写入失败");
}
#[cfg(test)]
mod tests {
#[test]
fn test_get_bing_image() {
crate::get_bing_image("/home/xxx/a.jpg".to_string());
}
}