从网站的.NET / C#下载图片下载图片、网站、NET

2023-09-02 01:24:33 作者:失约于我

我想从网站上下载的图像。我现在用的就是做工精细,同时图像可在code。如果图像是不存在,它是创造一个问题。如何验证图像的可用性?

code:

方法1:

 的WebRequest requestPic = WebRequest.Create(IMAGEURL);

WebResponse类responsePic = requestPic.GetResponse();

图像webImage = Image.FromStream(responsePic.GetResponseStream()); // 错误

webImage.Save(D:\ \影像书\+文件名+.JPG);
 

方法2:

  Web客户端的客户端=新的Web客户端();
流流= client.OpenRead(IMAGEURL);

位图=新位图(流); //错误:参数无效。
stream.Flush();
stream.Close();
client.dispose();

如果(位图!= NULL)
{
    bitmap.Save(D:\图片\+文件名+.JPG);
}
 

编辑:

流有如下语句:

 长度((System.Net.ConnectStream)(STR))。长度'引发了异常类型的System.NotSupportedException长{System.NotSupportedException}
    位置((System.Net.ConnectStream)(STR))。位置引发了异常类型的System.NotSupportedException长{System.NotSupportedException}
 ReadTimeout 300000 INT
WriteTimeout 300000 INT
 
如何批量下载网页图片的原图

解决方案

有没有必要让任何图像类,你可以简单地叫WebClient.DownloadFile:

 字符串localFilename = @C:了localPath  tofile.jpg;
使用(Web客户端的客户端=新的Web客户端())
{
    client.DownloadFile(http://www.example.com/image.jpg,localFilename);
}
 

更新 因为你将要检查文件是否存在,并下载该文件,如果是的话,最好是在同一个请求中做到这一点。所以在这里是一种方法,能做到这一点:

 私有静态无效DownloadRemoteImageFile(URI字符串,字符串文件名)
{
    HttpWebRequest的要求=(HttpWebRequest的)WebRequest.Create(URI);
    HttpWebResponse响应=(HttpWebResponse)request.GetResponse();

    //检查远程文件被发现。将contentType
    //检查由于用于一个不存在的请求执行
    //图像文件可能被重定向到404页,其将
    //产生状态codeOK,即使图像不
    //找到。
    如果((response.Status code ==的HTTPStatus code.OK ||
        response.Status code ==的HTTPStatus code.Moved ||
        response.Status code ==的HTTPStatus code.Redirect)及和放大器;
        response.ContentType.StartsWith(形象,StringComparison.OrdinalIgnoreCase))
    {

        //如果找到远程文件,下载OIT
        使用(流的InputStream = response.GetResponseStream())
        使用(流的OutputStream = File.OpenWrite(文件名))
        {
            byte []的缓冲区=新的字节[4096];
            INT读取动作;
            做
            {
                读取动作= inputStream.Read(缓冲液,0,buffer.Length);
                outputStream.Write(缓冲液,0,读取动作);
            }而(读取动作!= 0);
        }
    }
}
 

在简单地说,它使该文件的请求,验证响应code是确定感动的一个重定向的也的是,的ContentType 是一个图像。如果这些条件都为真,该文件下载。

I am trying to download images from the site. The code which I am using is working fine while the image is available. If the image it not available it is creating a problem. How to validate availability of the image?

Code:

Method 1:

WebRequest requestPic = WebRequest.Create(imageUrl);

WebResponse responsePic = requestPic.GetResponse();

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

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

Method 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:

Stream has the following statements:

      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

解决方案

There is no need to involve any image classes, you can simply call WebClient.DownloadFile:

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

Update Since you will want to check whether the file exists and download the file if it does, it's better to do this within the same request. So here is a method that will do that:

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

In brief, it makes a request for the file, verifies that the response code is one of OK, Moved or Redirect and also that the ContentType is an image. If those conditions are true, the file is downloaded.