c# - 从 .NET/C# 中的站点下载图像

标签 c# .net image streaming

我正在尝试从站点下载图像。当图像可用时,我使用的代码工作正常。如果图像不可用,则会产生问题。如何验证图像的可用性?

代码:

方法一:

WebRequest requestPic = WebRequest.Create(imageUrl);

WebResponse responsePic = requestPic.GetResponse();

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

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

方法二:

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

简而言之,它请求文件,验证响应代码是OKMovedRedirect 之一 并且 ContentType 是一张图片。如果满足这些条件,则下载文件。

关于c# - 从 .NET/C# 中的站点下载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3615800/

相关文章:

出于性能原因,C# 字典在一次调用中添加/设置

c# - 如何将存储过程中的大量参数从代码传递给SQL Server

c# - 检查滚动条可见性

c# - 从基本 URI 和相对路径创建新的 URI - 斜线有区别吗?

.net - SiteMapPath 没有出现

python tkinter : displays only a portion of an image

java - 为什么应该使用 JLabel 而不是 Image?

c# - 为什么路径正在改变

c# - 缩小文件路径以更易于阅读的功能

javascript - 另存为与 CSS 混合的图像 Canvas