c# - 如何从网址下载图片

标签 c# url download

如果 url 的链接末尾没有图像格式,是否可以直接从 c# 中的 url 下载图像?网址示例:

https://fbcdn-sphotos-h-a.akamaihd.net/hphotos-ak-xpf1/v/t34.0-12/10555140_10201501435212873_1318258071_n.jpg?oh=97ebc03895b7acee9aebbde7d6b002bf&oe=53C9ABB0&__gda__=1405685729_110e04e71d969d392b63b27ec4f4b24a

当 url 以图像格式结尾时,我知道如何下载图像。例如:

http://img1.wikia.nocookie.net/__cb20101219155130/uncyclopedia/images/7/70/Facebooklogin.png

最佳答案

简单 您可以使用以下方法。

using (WebClient client = new WebClient()) 
{
    client.DownloadFile(new Uri(url), @"c:\temp\image35.png");
    // OR 
    client.DownloadFileAsync(new Uri(url), @"c:\temp\image35.png");
}

这些方法几乎与 DownloadString(..) 和 DownloadStringAsync(...) 相同。他们将文件存储在目录中而不是 C# 字符串中,并且不需要 URi 中的格式扩展

如果您不知道图像的格式(.png、.jpeg 等)

public void SaveImage(string imageUrl, string filename, ImageFormat format)
{    
    WebClient client = new WebClient();
    Stream stream = client.OpenRead(imageUrl);
    Bitmap bitmap;  bitmap = new Bitmap(stream);

    if (bitmap != null)
    {
        bitmap.Save(filename, format);
    }
        
    stream.Flush();
    stream.Close();
    client.Dispose();
}

使用它

try
{
    SaveImage("--- Any Image URL---", "--- Any Image Path ---", ImageFormat.Png)
}
catch(ExternalException)
{
    // Something is wrong with Format -- Maybe required Format is not 
    // applicable here
}
catch(ArgumentNullException)
{   
    // Something wrong with Stream
}

关于c# - 如何从网址下载图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24797485/

相关文章:

download - 无法从 gmail 下载包含可执行 Jar 的 Zip 文件

security - AWS S3 作为超链接的签名 URL 的安全性

c# - 如何从 SkyDrive 下载文件到 IsolatedStorage?

c# - 如何从 ASP.NET 5 MVC 6 Controller 操作返回 Javascript

c# - MethodBase.GetCurrentMethod() 性能?

c# - 检查系统中是否安装了 MSWord

.htaccess - 使用 htaccess 从基本 URL 中删除变量

asp.net-mvc - Url.Content() 不适用于复杂的 URL

c# - 什么是 C# 中的 Bootstrappers/Bootstrapping

jquery - Hash to hide div - 直接访问页面URL