C# 从.NET/C中的站点下载图像#

C# 从.NET/C中的站点下载图像#,c#,.net,image,streaming,C#,.net,Image,Streaming,我正在尝试从网站下载图片。我使用的代码在图像可用时工作正常。如果图像不可用,则会产生问题。如何验证映像的可用性 代码: 方法1: WebRequest requestPic = WebRequest.Create(imageUrl); WebResponse responsePic = requestPic.GetResponse(); Image webImage = Image.FromStream(responsePic.GetResponseStream()); // Error

我正在尝试从网站下载图片。我使用的代码在图像可用时工作正常。如果图像不可用,则会产生问题。如何验证映像的可用性

代码:

方法1:

WebRequest requestPic = WebRequest.Create(imageUrl);

WebResponse responsePic = requestPic.GetResponse();

Image webImage = Image.FromStream(responsePic.GetResponseStream()); // Error

webImage.Save("D:\\Images\\Book\\" + fileName + ".jpg");
方法2:

WebClient client = new WebClient();
Stream stream = client.OpenRead(imageUrl);

bitmap = new Bitmap(stream); // Error : Parameter is not valid.
stream.Flush();
stream.Close();
client.dispose();

if (bitmap != null)
{
    bitmap.Save("D:\\Images\\" + fileName + ".jpg");
}
编辑:

流具有以下语句:

      Length  '((System.Net.ConnectStream)(str)).Length' threw an exception of type  'System.NotSupportedException'    long {System.NotSupportedException}
    Position  '((System.Net.ConnectStream)(str)).Position' threw an exception of type 'System.NotSupportedException'    long {System.NotSupportedException}
 ReadTimeout  300000    int
WriteTimeout  300000    int

无需涉及任何图像类,您只需调用:


更新
由于您需要检查文件是否存在,如果存在,则下载文件,因此最好在相同的请求中执行此操作。这里有一个方法可以做到这一点:

private static void DownloadRemoteImageFile(string uri, string fileName)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    // Check that the remote file was found. The ContentType
    // check is performed since a request for a non-existent
    // image file might be redirected to a 404-page, which would
    // yield the StatusCode "OK", even though the image was not
    // found.
    if ((response.StatusCode == HttpStatusCode.OK || 
        response.StatusCode == HttpStatusCode.Moved || 
        response.StatusCode == HttpStatusCode.Redirect) &&
        response.ContentType.StartsWith("image",StringComparison.OrdinalIgnoreCase))
    {

        // if the remote file was found, download oit
        using (Stream inputStream = response.GetResponseStream())
        using (Stream outputStream = File.OpenWrite(fileName))
        {
            byte[] buffer = new byte[4096];
            int bytesRead;
            do
            {
                bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                outputStream.Write(buffer, 0, bytesRead);
            } while (bytesRead != 0);
        }
    }
}

简而言之,它请求文件,验证响应代码是否为
OK
Moved
Redirect
之一,以及
ContentType
是否为图像。如果这些条件为真,则下载该文件。

我在一个项目中使用了上面Fredrik的代码,并做了一些轻微的修改,我想与大家分享一下:

private static bool DownloadRemoteImageFile(string uri, string fileName)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    HttpWebResponse response;
    try
    {
        response = (HttpWebResponse)request.GetResponse();
    }
    catch (Exception)
    {
        return false;
    }

    // Check that the remote file was found. The ContentType
    // check is performed since a request for a non-existent
    // image file might be redirected to a 404-page, which would
    // yield the StatusCode "OK", even though the image was not
    // found.
    if ((response.StatusCode == HttpStatusCode.OK ||
        response.StatusCode == HttpStatusCode.Moved ||
        response.StatusCode == HttpStatusCode.Redirect) &&
        response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
    {

        // if the remote file was found, download it
        using (Stream inputStream = response.GetResponseStream())
        using (Stream outputStream = File.OpenWrite(fileName))
        {
            byte[] buffer = new byte[4096];
            int bytesRead;
            do
            {
                bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                outputStream.Write(buffer, 0, bytesRead);
            } while (bytesRead != 0);
        }
        return true;
    }
    else
        return false;
}
主要变化是:

  • 对GetResponse()使用try/catch,因为当远程文件返回404时,我遇到了一个异常
  • 返回布尔值

    • 也可以使用下载数据方法

          private byte[] GetImage(string iconPath)
          {
              using (WebClient client = new WebClient())
              {
                  byte[] pic = client.DownloadData(iconPath);
                  //string checkPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +@"\1.png";
                  //File.WriteAllBytes(checkPath, pic);
                  return pic;
              }
          }
      

      从服务器或网站下载图像并在本地存储的最佳实践

      WebClient client=new Webclient();
      client.DownloadFile("WebSite URL","C:\\....image.jpg");
      client.Dispose();
      
      您可以使用此代码

      using (WebClient client = new WebClient()) {
                          Stream stream = client.OpenRead(imgUrl);
                          if (stream != null) {
                              Bitmap bitmap = new Bitmap(stream);
                              ImageFormat imageFormat = ImageFormat.Jpeg;
                              if (bitmap.RawFormat.Equals(ImageFormat.Png)) {
                                  imageFormat = ImageFormat.Png;
                              }
                              else if (bitmap.RawFormat.Equals(ImageFormat.Bmp)) {
                                  imageFormat = ImageFormat.Bmp;
                              }
                              else if (bitmap.RawFormat.Equals(ImageFormat.Gif)) {
                                  imageFormat = ImageFormat.Gif;
                              }
                              else if (bitmap.RawFormat.Equals(ImageFormat.Tiff)) {
                                  imageFormat = ImageFormat.Tiff;
                              }
      
                              bitmap.Save(fileName, imageFormat);
                              stream.Flush();
                              stream.Close();
                              client.Dispose();
                          }
                      }
      

      项目位于:

      别忘了处理
      网络客户端
      @Geetha:如果您尝试在web浏览器中导航到给定的URL,是否会获得图像?@Geetha:听起来好像您首先要检查图像是否存在,然后下载它。对于第一步,检查这里:它花费了太多的时间,而且下载空白图像。线位图=新位图(流);显示错误:参数无效“不需要涉及任何图像类”。实际上,如果你的目的是下载一个图像,对它进行操作,然后简单地显示它,这是有必要的。如果不需要存储文件,则不需要存储文件,甚至不需要在磁盘中填充图像。请使用
      try-catch
      将有问题的语句包装起来,并向我们提供异常详细信息。行位图=新位图(流);显示错误:参数无效。谢谢-看起来像是编写良好的代码,在我的应用程序中运行良好。当可以引发异常时,为什么要返回布尔标志?在性能出现问题之前,它总是更好的。SRP不允许有这些方法。也许您可以解释一下这段代码,以及它为什么工作?
      WebClient client=new Webclient();
      client.DownloadFile("WebSite URL","C:\\....image.jpg");
      client.Dispose();
      
      using (WebClient client = new WebClient()) {
                          Stream stream = client.OpenRead(imgUrl);
                          if (stream != null) {
                              Bitmap bitmap = new Bitmap(stream);
                              ImageFormat imageFormat = ImageFormat.Jpeg;
                              if (bitmap.RawFormat.Equals(ImageFormat.Png)) {
                                  imageFormat = ImageFormat.Png;
                              }
                              else if (bitmap.RawFormat.Equals(ImageFormat.Bmp)) {
                                  imageFormat = ImageFormat.Bmp;
                              }
                              else if (bitmap.RawFormat.Equals(ImageFormat.Gif)) {
                                  imageFormat = ImageFormat.Gif;
                              }
                              else if (bitmap.RawFormat.Equals(ImageFormat.Tiff)) {
                                  imageFormat = ImageFormat.Tiff;
                              }
      
                              bitmap.Save(fileName, imageFormat);
                              stream.Flush();
                              stream.Close();
                              client.Dispose();
                          }
                      }