gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:44:13 26 4
gpt4 key购买 nike

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

代码:

方法一:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com