【问题标题】:Using a WebClient to save an image with the appropriate extension使用 WebClient 保存具有适当扩展名的图像
【发布时间】:2013-08-31 01:16:36
【问题描述】:

我需要从网站检索图像并将其保存到我的本地文件夹。图像类型在 .png、.jpg 和 .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 吗?如果是这样,你是怎么做到的?

【问题讨论】:

  • 你需要给文件名加上路径@"/project1/home_image/Someimage.png"
  • 我不知道扩展名,这就是我需要找出的,以便我可以用正确的扩展名保存它。
  • 您需要从响应的标头中获取 mime 类型,将其映射到扩展并使用它。不幸的是,WebClient 方法太高级,无法让您访问标题。
  • 在这种情况下您需要使用HttpWebRequest。但我的问题是,如果您知道需要下载的图像,您不妨知道扩展程序!您的服务方法是否流式传输图像?

标签: c# .net image webclient


【解决方案1】:

如果要使用WebClient,则必须从WebClient.ResponseHeaders 中提取标头信息。您必须先将其存储为字节数组,然后在获取文件信息后保存文件。

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 个字母......个人喜好。如果它不打扰您,您可以将整个 switch 语句替换为:

saveloc += "." + fileType.Substring(fileType.IndexOf('/') + 1);

使代码更整洁。

【讨论】:

  • 对于 ppm 文件,mime 类型是 image/x-portable-pixmap,因此第二个选项将生成一个“.x-portable-pixmap”文件,它可能不会与您的图像相关联程序。
【解决方案2】:

试试这样的

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create("Your URL");
 request.Method = "GET";
 var response = request.GetResponse();
 var contenttype = response.Headers["Content-Type"]; //Get the content type and extract the extension.
 var stream = response.GetResponseStream();

然后保存流

【讨论】:

    猜你喜欢
    • 2010-11-15
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 2015-11-15
    相关资源
    最近更新 更多