Home >Backend Development >C#.Net Tutorial >Baidu image batch download tool based on C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System .Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Image Downloader{
Form1: Form {
use using using using using using using using using using out out through out through off‐through off ‐ ‐ ‐ ‐‐ ‐ InitializeComponent();
}
using use using using using using using using using through out through out using ‐ off off ‐ private ‐ void ‐‐‐‐‐ private void butSelect_Click(object sender, EventArgs e) { OK) {
;
+ "pagen");
private void butStart_Click( object sender , EventArgs e) {
string key = textKeyWords.Text;
using using using using using using using using through out through out through out through off ’ s to using right through to ‐ ‐ ‐‐‐‐‐‐ long to be to be found. ");
return; ;
return;
process(key);
}); ; for (int i = 0 ; i HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://image.baidu.com/search/avatarjson?tn=resultjsonavatarnew&ie=utf-8&word=" + Uri.EscapeUriString(key) + "&cg=girl&pn=" + (i + 1) * 60 + "&rn=60&itg=0&z=0&fr=&width=&height=&lm=-1&ic=0&s=0&st=-1&gsm=360600003c");
using (HttpWebResponse res = (HttpWebResponse)req.GetResponse()) {
if (res.StatusCode == HttpStatusCode.OK) {
using (Stream stream = res.GetResponseStream()) {
try {
download(stream);
} catch (Exception e) {
textShow.BeginInvoke(new Action(() => {
textShow.AppendText(e.Message + Environment.NewLine);
}));
}
}
} else {
MessageBox.Show("获取第" + i + "页失败!" + res.StatusCode);
}
}
}
}
private void download(Stream stream) {
using (StreamReader reader = new StreamReader(stream)) {
string json = reader.ReadToEnd();
JObject objRoot = (JObject)JsonConvert.DeserializeObject(json);
JArray imgs = (JArray)objRoot["imgs"];
for (int j = 0 ; j JObject img = (JObject)imgs[j];
string objUrl = (string)img["objURL"];//http://hibiadu....../1.jpg
// textShow.AppendText(objUrl + Environment.NewLine);
//保存的路径是:destDir;
try {
DownloadImage(objUrl);//Avoid the code in a method being too complex
textShow.BeginInvoke(new Action(() => {
textShow.AppendText(ex.Message + Environment.NewLine); (dir, Path.GetFileName(objUrl));
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(objUrl); Sent from Baidu Pictures using (HttpWebResponse res = (HttpWebResponse)req.GetResponse()) {
using (Stream stream = res.GetResponseStream()) filestream = new FileStream(path, FileMode.Create)) {
throw new Exception("Download failed" + res.StatusCode);
}