Скачать изображение с сайта in.NET/C#
Я пытаюсь загрузить изображения с сайта. Код, который я использую работает нормально, пока изображение доступно. Если изображение не доступно, это создает проблемы. Как проверить доступность образа?
код:
Способ 1:
WebRequest requestPic = WebRequest.Create(imageUrl);
WebResponse responsePic = requestPic.GetResponse();
Image webImage = Image.FromStream(responsePic.GetResponseStream()); // Error
webImage.Save("D:ImagesBook" + 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");
}
Edit:
поток имеет следующие высказывания:
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
4 ответов:
нет необходимости привлекать какие-либо классы изображений, вы можете просто позвонить
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); } } }короче говоря, он делает запрос на файл, проверяет, что код ответа является одним из
OK,MovedилиRedirectи чтоContentTypeизображение. Если эти условия верны, файл загружается.
я использовал код Фредрика выше в проекте с некоторыми небольшими изменениями, думал, что поделюсь:
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; }основные изменения:
- С помощью try / catch для GetResponse () как я был запущен в исключение, когда удаленный файл вернулся 404
- возврат логического
также можно использовать метод DownloadData
private byte[] GetImage(string iconPath) { using (WebClient client = new WebClient()) { byte[] pic = client.DownloadData(iconPath); //string checkPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +@".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); } } }
Comments