从.NET / C#下载图片

我正试图从网站上下载图片。 我使用的代码工作正常,而图像是可用的。 如果图片不可用,则会造成问题。 如何validation图像的可用性?

码:

方法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"); } 

编辑:

stream有以下陈述:

  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 

不需要涉及任何图像类,您可以简单地调用WebClient.DownloadFile

 string localFilename = @"c:\localpath\tofile.jpg"; using(WebClient client = new WebClient()) { client.DownloadFile("http://www.example.com/image.jpg", localFilename); } 

更新
既然你会想检查文件是否存在,如果是的话就下载这个文件,最好在同一个请求中这样做。 所以这里有一个方法可以做到这一点:

 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); } } } 

简而言之,它会对文件进行请求,validation响应代码是“ 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时,我正在运行一个exception
  • 返回一个布尔值

也可以使用DownloadData方法

  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; } } 
  private static void DownloadRemoteImageFile(string uri, string fileName) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if ((response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Moved || response.StatusCode == HttpStatusCode.Redirect) && response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase)) { 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); } } }