Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/275.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从URL下载图像_C#_Url_Download - Fatal编程技术网

C# 如何从URL下载图像

C# 如何从URL下载图像,c#,url,download,C#,Url,Download,如果链接末尾的url没有图像格式,有没有办法直接从c#中的url下载图像?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_110e04e71d969d392b63b

如果链接末尾的url没有图像格式,有没有办法直接从c#中的url下载图像?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
<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
我知道当url以图像格式结尾时如何下载图像。例如:

http://img1.wikia.nocookie.net/__cb20101219155130/uncyclopedia/images/7/70/Facebooklogin.png
<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>

根据您是否了解图像格式,以下是您可以使用的方法:

<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
了解图像格式,将图像下载到文件中 在不知道图像格式的情况下将图像下载到文件 您可以使用加载任何类型的常用位图(jpg、png、bmp、gif等),它将自动检测文件类型,您甚至不需要检查url扩展名(这不是一个很好的做法)。例如:

<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
注意:如果下载的内容不是已知的图像类型,则Image.FromStream可能引发ArgumentException

<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
选中以查找所有可用的格式。 以下是对和的参考。

简单地说
<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
您可以使用以下方法

<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
使用(WebClient=newWebClient())
{
client.DownloadFile(新的Uri(url),@“c:\temp\image35.png”);
//或
client.DownloadFileAsync(新的Uri(url),@“c:\temp\image35.png”);
}
这些方法与DownloadString(…)和DownloadStringAsync(…)几乎相同。它们将文件存储在目录中而不是C#字符串中,并且不需要URi中的格式扩展

<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
如果您不知道图像的格式(.png、.jpeg等)
public void SaveImage(字符串imageUrl、字符串文件名、ImageFormat格式)
{    
WebClient客户端=新的WebClient();
Stream=client.OpenRead(imageUrl);
位图位图;位图=新位图(流);
if(位图!=null)
{
保存(文件名、格式);
}
stream.Flush();
stream.Close();
client.Dispose();
}
使用它
试试看
{
SaveImage(“---任何图像URL----”,“---任何图像路径----”,ImageFormat.Png)
}
捕获(外部异常)
{
//格式有问题--可能不是必需的格式
//适用于此
}
捕获(异常)
{   
//流有什么问题吗
}

.net Framework允许PictureBox控件从url加载图像

<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
并在Laod完成事件中保存图像

protected void LoadImage() {
 pictureBox1.ImageLocation = "PROXY_URL;}

void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e) {
   pictureBox1.Image.Save(destination); }
<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>

试试这个它对我有用

<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
把这个写在你的控制器里

public class DemoController: Controller

        public async Task<FileStreamResult> GetLogoImage(string logoimage)
        {
            string str = "" ;
            var filePath = Server.MapPath("~/App_Data/" + SubfolderName);//If subfolder exist otherwise leave.
            // DirectoryInfo dir = new DirectoryInfo(filePath);
            string[] filePaths = Directory.GetFiles(@filePath, "*.*");
            foreach (var fileTemp in filePaths)
            {
                  str= fileTemp.ToString();
            }
                return File(new MemoryStream(System.IO.File.ReadAllBytes(str)), System.Web.MimeMapping.GetMimeMapping(str), Path.GetFileName(str));
        }
<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
公共类DemoController:控制器
公共异步任务GetLogoImage(字符串logoimage)
{
字符串str=“”;
var filePath=Server.MapPath(“~/App_Data/”+子文件夹名);//如果子文件夹存在,则离开。
//DirectoryInfo dir=新的DirectoryInfo(filePath);
字符串[]filePath=Directory.GetFiles(@filePath,*.*);
foreach(文件路径中的var fileTemp)
{
str=fileTemp.ToString();
}
返回文件(newmemorystream(System.IO.File.ReadAllBytes(str)),System.Web.MimeMapping.GetMimeMapping(str),Path.GetFileName(str));
}
这是我的看法

<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>

对于希望下载图像而不将其保存到文件中的任何人:

<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
Image DownloadImage(string fromUrl)
{
    using (System.Net.WebClient webClient = new System.Net.WebClient())
    {
        using (Stream stream = webClient.OpenRead(fromUrl))
        {
            return Image.FromStream(stream);
        }
    }
}

我发现的大多数帖子在第二次迭代后都会超时。特别是如果你像我一样在一堆if图像中循环。因此,改进上述建议的整个方法如下:

<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
public System.Drawing.Image DownloadImage(string imageUrl)
    {
        System.Drawing.Image image = null;

        try
        {
            System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(imageUrl);
            webRequest.AllowWriteStreamBuffering = true;
            webRequest.Timeout = 30000;
            webRequest.ServicePoint.ConnectionLeaseTimeout = 5000;
            webRequest.ServicePoint.MaxIdleTime = 5000;

            using (System.Net.WebResponse webResponse = webRequest.GetResponse())
            {

                using (System.IO.Stream stream = webResponse.GetResponseStream())
                {
                    image = System.Drawing.Image.FromStream(stream);
                }
            }

            webRequest.ServicePoint.CloseConnectionGroup(webRequest.ConnectionGroupName);
            webRequest = null; 
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message, ex);

        }


        return image;
    }

.NET在过去几年中发生了一些变化,使得这篇文章的其他答案变得相当过时:

<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
  • 他们使用
    System.Drawing
    (不适用于.NET Core)中的
    图像
    来查找图像格式
  • 他们使用
    System.Net.WebClient
    ,这是
我们不建议您在新开发中使用
WebClient
类。相反,使用类

<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
.NET核心异步解决方案 获取文件扩展名 获取文件扩展名的第一部分是从URL中删除所有不必要的部分。 我们可以使用URIPROTIAL.Path来获取从
方案到
路径的所有内容
换句话说,
https://www.example.com/image.png?query&with.dots
变为
https://www.example.com/image.png

<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
之后,我们可以使用只获取扩展名(在我前面的示例中,
.png

<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
var uriWithoutQuery=uri.GetLeftPart(UriPartial.Path);
var fileExtension=Path.GetExtension(uriWithoutQuery);
下载图像 从这里开始应该是直截了当的。使用下载映像,创建路径,确保目录存在,然后使用将字节写入路径

<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
私有异步任务下载ImageAsync(字符串目录路径、字符串文件名、Uri)
{
使用var httpClient=new httpClient();
//获取文件扩展名
var uriWithoutQuery=uri.GetLeftPart(UriPartial.Path);
var fileExtension=Path.GetExtension(uriWithoutQuery);
//创建文件路径并确保目录存在
var path=path.Combine(directoryPath,$“{fileName}{fileExtension}”);
CreateDirectory(directoryPath);
//下载图像并写入文件
var imageBytes=wait httpClient.GetByteArrayAsync(uri);
wait File.writeAllBytes同步(路径,imageBytes);
}
请注意,您需要使用以下指令

<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
使用系统;
使用System.IO;
使用System.Threading.Tasks;
使用System.Net.Http;
示例用法
var folder=“images”;
var fileName=“test”;
变量url=”https://cdn.discordapp.com/attachments/458291463663386646/592779619212460054/Screenshot_20190624-201411.jpg?query&with.dots";
等待下载ImageAsync(文件夹、文件名、新Uri(url));
笔记
  • 为每个方法调用创建一个新的
    HttpClient
    是一种不好的做法。它应该在整个应用程序中重用。我编写了一个简短的
    ImageDownloader
    (50行)示例,其中包含更多文档,可以正确地重用
    HttpClient
    ,并正确地处理您可以找到的内容
请注意,您需要“使用System.Draw”