源代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Collections;
namespace WindowsFormsApplication14
{
public partial class Form1 : Form
{
public struct param
{
public int js;
public string url;
}
public delegate void listview1AddImg(String imgname,int js);
public listview1AddImg myDelegate;
public Form1()
{
InitializeComponent();
this.imageList1.ImageSize = new Size(130, 130);
this.listView1.LargeImageList = this.imageList1;
myDelegate = new listview1AddImg(listview1AddImgMethod);
}
p rivate void button1_Click(object sender, EventArgs e)
{
this.listView1.Items.Clear();
String url = @"http://image.baidu.com/i?tn=baiduimage&ct=201326592&cl=2&lm=-1&fr=&pv=&ic=0&z=0&word=%C3%C0%C5%AE&s=0";
Thread myThread1 = new Thread(downimg);
myThread1.Start((object)url);
}
p rivate void downimg(object url)
{
String imgUrl = null;
int js1=0;
param param1=new param();
WebClient web1 = new WebClient();
byte[] data1= web1.DownloadData((String)url);
String html = Encoding.Default.GetString(data1);
//从网页源码中分析出图片,并且投入线程池
MatchCollection m1 = Regex.Matches(html, @"<img\s+name='pn\d+'\s+src=""(?<smallpic>[\w:/\.,&=]*)",RegexOptions.IgnoreCase);
foreach (Match m in m1)
{
param1.js = js1;
js1++;
imgUrl = m.Groups["smallpic"].ToString();
param1.url = imgUrl;
ThreadPool.QueueUserWorkItem(new WaitCallback(dowork),(object)param1);
}
}
p rivate void dowork(object list1)
{
//下载图片
String imgname=null;
param param1 = new param();
param1= (param)list1 ;
WebClient web1 = new WebClient();
//Bitmap bmp = new Bitmap(web1.OpenRead(param1.url));
imgname = param1.js.ToString() + ".jpg";
web1.DownloadFile(param1.url, Application.StartupPath + "\\" +imgname);
this.listView1.Invoke(this.myDelegate, new object[] {imgname,param1.js});
}
******* void listview1AddImgMethod(String imgname,int js)
{
try
{
this.imageList1.Images.Add(Image.FromFile(Application.StartupPath + "\\" + imgname));
this.listView1.Items.Add(imgname);
this.listView1.Items[js].ImageIndex = js;
Debug.WriteLine(js);
Debug.WriteLine(imgname);
}
catch(Exception e)
{
Debug.WriteLine(e.Message);
}
}
}
}