有时,我们看到比较好的漂亮图片壁纸,风景图画等,可能需要从固定的网址下载图片。如果一个网页一个网页地打开然后另存为我们的文件名,很费时。有没有批量下载的办法呢?有的!但前提是:图片的路径及文件名有规律。
当然,你可以使用网际快车或迅雷的批量下载功能,不在本文讨论之列。
这里利用了 WebClient的DownloadFile方法,由于代码比较简单,我就不多说。
// BatchDownload.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="BatchDownload.aspx.cs" Inherits="_Default" Debug="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>批量图片下载网页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
// BatchDownload.asp.cs
using System;
using System.Data;
using System.Drawing;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
int m = 0;
for (int i = 1; i < 200; i++)
{
for (int j = 1; j < 100; j++)
{
string folder;
if(i < 100)
{
folder = i.ToString("000");
}
else
{
folder = i.ToString("0000");
}
string uriString = "http://www.photodownloadsite.com/200702/" + folder + @"/" + j.ToString() + @".jpg?http://www.xvna.com";
Uri address = new Uri(uriString);
string fileName = "a" + i.ToString("000") + m.ToString("00000") + ".jpg?http://www.xvna.com";
WebClient wc = new WebClient();
try
{
//Bitmap bmp = new Bitmap(wc.OpenRead(address));
wc.DownloadFile(address, Server.MapPath(fileName));
}
catch (Exception exc)
{
}
finally
{
if (wc != null) wc.Dispose();
}
//sb.Append(uriString + "<br/>" + Server.MapPath(fileName) + "<br/>");
//sb.Append("<img src='" + uriString + "'><br/>");
m++;
}
}
//Label1.Text = sb.ToString();
}
}
这里出一个思考题:
如果想要下载图片高度、宽度大于某个指定尺寸大小的图片呢,应该如何做?想一想。实际上,上面这句已大致提示了相关的做法了://Bitmap bmp = new Bitmap(wc.OpenRead(address));
这里不妨再引申一下:
如果需要即时获取如下图类似的股票价格图,又如何做呢?