如何从 URL 下载图像 [英] How to download image from URL

查看:28
本文介绍了如何从 URL 下载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果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:	empimage35.png");//或者client.DownloadFileAsync(new Uri(url), @c:	empimage35.png");}

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

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

public void SaveImage(string imageUrl, string filename, ImageFormat format){WebClient 客户端 = new WebClient();流流 = client.OpenRead(imageUrl);位图位图;位图 = 新位图(流);如果(位图!= null){位图.保存(文件名,格式);}流.Flush();流.关闭();客户端处理();}

使用它

试试{SaveImage("---任意图片URL---", "---任意图片路径---", ImageFormat.Png)}捕获(外部异常){//格式有问题——可能不是必需的格式//此处适用}catch(ArgumentNullException){//Stream 有问题}

Is there a way to download an image directly from a url in c# if the url does not have an image format at the end of the link? Example of 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

I know how to download the image when the url ends with an image format. Eg:

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

解决方案

Simply You can use following methods.

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

These methods are almost same as DownloadString(..) and DownloadStringAsync(...). They store the file in Directory rather than in C# string and no need of Format extension in URi

If You don't know the Format(.png, .jpeg etc) of Image

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

Using it

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
}

这篇关于如何从 URL 下载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆