使用WebClient保存具有适当扩展名的图像 [英] Using a WebClient to save an image with the appropriate extension
问题描述
我需要检索并将图像从网站保存到我的本地文件夹。图像类型在.png,.jpg和.gif之间变化
I'm required to retrieve and save an image from a website to my local folder. The image type varies between .png, .jpg and .gif
我尝试过使用
string url = @"http://redsox.tcs.auckland.ac.nz/CSS/CSService.svc/";
string saveLoc = @"/project1/home_image";
using (var wc = new WebClient())
{
wc.DownloadFile(url, saveLoc);
}
但这会将文件'home_image'保存在没有扩展名的文件夹中。我的问题是你如何确定扩展名?有一个简单的方法吗?可以使用HTTP请求的Content-Type吗?如果是这样,你怎么做?
but this saves the file 'home_image' in the folder without the extension. My question is how do you determine the extension? Is there a simple way to do this? Can one use the Content-Type of the HTTP request? If so, how do you do this?
推荐答案
如果你想使用 WebClient
,然后你必须从 WebClient.ResponseHeaders
中提取标题信息。您必须先将其存储为字节数组,然后在获取文件信息后保存文件。
If you want to use a WebClient
, then you have to extract the header information from WebClient.ResponseHeaders
. You'll have to store it as a byte array first, and then save the file after getting your file information.
string url = @"http://redsox.tcs.auckland.ac.nz/CSS/CSService.svc/";
string saveLoc = @"/project1/home_image";
using (WebClient wc = new WebClient())
{
byte[] fileBytes = wc.DownloadData(url);
string fileType = wc.ResponseHeaders[HttpResponseHeader.ContentType];
if (fileType != null)
{
switch (fileType)
{
case "image/jpeg":
saveloc += ".jpg";
break;
case "image/gif":
saveloc += ".gif";
break;
case "image/png":
saveloc += ".png";
break;
default:
break;
}
System.IO.File.WriteAllBytes(saveloc, fileBytes);
}
}
我喜欢我的扩展名为3个字母,如果他们可以....个人偏好。如果它不打扰你,你可以用以下代码替换整个开关
语句:
I like my extensions to be 3 letters long if they can.... personal preference. If it doesn't bother you, you can replace the entire switch
statement with:
saveloc += "." + fileType.Substring(fileType.IndexOf('/') + 1);
使代码更整洁。
这篇关于使用WebClient保存具有适当扩展名的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!