如何获取网页中的图片文件?并显示在WinForm中

yuson_yan 2006-11-09 11:34:46
假设有N个网页,每个网页上面有一张图片,有什么办法可以将这些网页保存到数据库中呀?

关键是怎么获取这些图片文件?
...全文
448 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
shizhiyunanswer 2006-11-10
  • 打赏
  • 举报
回复
给你解决方案:
//下载文件
public static byte[] DownLoadFile(string FileUrl)
{
long fbyte;

WebRequest wr = WebRequest.Create(FileUrl);
WebResponse wre = wr.GetResponse();
fbyte = wre.ContentLength;
wre.Close();
WebClient wc = new WebClient();
wc.DownloadData(FileUrl);
Stream s = wc.OpenRead(FileUrl);
byte[] byt = new byte[fbyte];
int allbyt = (int)(byt.Length);
int statbyte = 0;
while (fbyte > 0)
{
int m = s.Read(byt, statbyte, allbyt);
if (m == 0) break;
statbyte += m;
allbyt -= m;

}
/// 下面是将文件保存到本地磁盘 如果你要放到数据库中就注释掉下面的代码
FileStream fstr = new FileStream(@"C:\dwd.jpg", FileMode.OpenOrCreate, FileAccess.Write);
fstr.Write(byt, 0, statbyte);
s.Close();
fstr.Close();
// MessageBox.Show("下载完成!", "下载完成", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
return byt; //返回字节数组供加入数据库时用
}


//添加入数据库

byte[] imgdata = DownLoadFile(string FileUrl);//也就是上面你得到的字节数组(byt)

ConnectionString ="Integrated Security=SSPI;" + "Initial Catalog=master;" +"Data Source=localhost;";
  conn.ConnectionString = ConnectionString;
try
  {
   string mySelectQuery = "INSERT INTO imagetest(imgtitle,imgdata) VALUES (@imgtitle, @imgdata )";

   SqlCommand myCommand = new SqlCommand(mySelectQuery, conn);
   SqlParameter paramTitle = new SqlParameter("@imgtitle", SqlDbType.VarChar,30 );
   paramTitle.Value = imgtitle;
   myCommand.Parameters.Add( paramTitle);
   SqlParameter paramData = new SqlParameter( "@imgdata", SqlDbType.Image );
   paramData.Value = imgdata;
   myCommand.Parameters.Add( paramData );
   conn.Open();
   int numRowsAffected = myCommand.ExecuteNonQuery();
   conn.Close();
MessageBox.Show("Image Has In DataBase");
  }
  catch(Exception err)
  {
   MessageBox.Show("您输入名称可能在数据库中已存在或输入为空,请检查!"+err.ToString() );
  }
  finally
  {}


//如果还有什么不明的,Q我:31959040
yuson_yan 2006-11-10
  • 打赏
  • 举报
回复
图片的URL如何获取呀?网页上的图片多数是相对地址来的喔?
luofix 2006-11-10
  • 打赏
  • 举报
回复
//给你一个程序的片断,希望能对你有所启发
//URLimage是你要取得的图片的url
void ReadURLImageToStream(string URLimage)
{
Uri uri;
WebRequest req;
WebResponse resp;
Stream str;
try
{
uri=new Uri(URLimage);
req=WebRequest.Create(uri);
resp=req.GetResponse();
str=resp.GetResponseStream();
}
catch
{
//异常的处理
}
Image img=Image.FromStream(str);
//对图片的处理
}

110,546

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧