C# 获取外网图片并保存到相对应路径
2024-07-21 02:26:23
供稿:网友
c# 获取外网图片并保存到相对应路径
public static int saveimagefromweb(string imgurl,string path,string filename)
...{
if(path.equals(""))
throw new exception("未指定保存文件的路径");
string imgname = imgurl.tostring().substring(imgurl.tostring().lastindexof("/")+1);
string defaulttype = ".jpg";
string[] imgtypes = new string[]...{".jpg",".jpeg",".png",".gif",".bmp"};
string imgtype = imgurl.tostring().substring(imgurl.tostring().lastindexof("."));
foreach (string it in imgtypes)
...{
if (imgtype.tolower().equals(it))
break;
if (it.equals(".bmp"))
imgtype = defaulttype;
}
httpwebrequest request = (httpwebrequest)webrequest.create(imgurl);
request.useragent = "mozilla/6.0 (msie 6.0; windows nt 5.1; natas.robot)";
request.timeout = 3000;
webresponse response = request.getresponse();
stream stream = response.getresponsestream();
if( response.contenttype.tolower().startswith("image/") )
...{
byte[] arraybyte = new byte[1024];
int imglong = (int)response.contentlength;
int l = 0;
if(filename == "")
filename = imgname;
filestream fso = new filestream(path+filename+imgtype,filemode.create);
while(l<imglong)
...{
int i = stream.read(arraybyte,0,1024);
fso.write(arraybyte,0,i);
l += i;
}
fso.close();
stream.close();
response.close();
return 1;
}
else
...{
return 0;
}
}