Scarica l’immagine dal sito in .NET / C #

Sto cercando di scaricare immagini dal sito. Il codice che sto usando funziona bene mentre l’immagine è disponibile. Se l’immagine non è disponibile, sta creando un problema. Come convalidare la disponibilità dell’immagine?

Codice:

Metodo 1:

WebRequest requestPic = WebRequest.Create(imageUrl); WebResponse responsePic = requestPic.GetResponse(); Image webImage = Image.FromStream(responsePic.GetResponseStream()); // Error webImage.Save("D:\\Images\\Book\\" + fileName + ".jpg"); 

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

Modificare:

    Stream ha le seguenti dichiarazioni:

      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 

    Non è necessario coinvolgere alcuna class immagine, puoi semplicemente chiamare WebClient.DownloadFile :

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

    Aggiornare
    Dato che vorrete verificare se il file esiste e scaricare il file se lo fa, è meglio farlo all’interno della stessa richiesta. Quindi ecco un metodo che lo farà:

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

    In breve, effettua una richiesta per il file, verifica che il codice di risposta sia OK , Moved o Redirect e che ContentType sia un’immagine. Se tali condizioni sono vere, il file viene scaricato.

    Ho usato il codice di Fredrik sopra in un progetto con alcune lievi modifiche, ho pensato di condividere:

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

    I principali cambiamenti sono:

    • utilizzando un try / catch per GetResponse () mentre eseguivo un’eccezione quando il file remoto restituiva 404
    • restituire un booleano

    È anche ansible utilizzare il metodo DownloadData

      private byte[] GetImage(string iconPath) { using (WebClient client = new WebClient()) { byte[] pic = client.DownloadData(iconPath); //string checkPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) [email protected]"\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); } } }