web-dev-qa-db-fra.com

Télécharger l'image du site en .NET/C #

J'essaie de télécharger des images du site. Le code que j'utilise fonctionne correctement tant que l'image est disponible. Si l'image n'est pas disponible, cela crée un problème. Comment valider la disponibilité de l'image?

Code:

Méthode 1:

WebRequest requestPic = WebRequest.Create(imageUrl);

WebResponse responsePic = requestPic.GetResponse();

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

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

Méthode 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");
}

Modifier:

Stream contient les déclarations suivantes:

      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
62
Geeth

Il n’est pas nécessaire d’impliquer des classes d’image, vous pouvez simplement appeler WebClient.DownloadFile :

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

Mettre à jour
Puisque vous voulez vérifier si le fichier existe et le télécharger si c'est le cas, il est préférable de le faire avec la même demande. Donc, voici une méthode qui fera cela:

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

En bref, il demande le fichier et vérifie que le code de réponse est l'un des OK, Moved ou Redirectet aussi que ContentType est une image. Si ces conditions sont remplies, le fichier est téléchargé.

159
Fredrik Mörk

J'ai utilisé le code de Fredrik ci-dessus dans un projet avec quelques légères modifications, pensant partager:

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

Les principaux changements sont les suivants:

  • en utilisant try/catch pour GetResponse () car je courais dans une exception lorsque le fichier distant retournait 404
  • retournant un booléen
26
germankiwi

Aussi possible d'utiliser la méthode 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;
        }
    }
2
Alexander Nikolaev
        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);
                }
            }
        }
0
CodeNinja

Il est recommandé de télécharger une image à partir du serveur ou du site Web et de la stocker localement.

WebClient client=new Webclient();
client.DownloadFile("WebSite URL","C:\\....image.jpg");
client.Dispose();
0
Mohamad-Al-Ibrahim