如何从网址下载图片

Ifw*_*him 86 c# url download

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

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
Run Code Online (Sandbox Code Playgroud)

我知道当网址以图像格式结束时如何下载图像.例如:

http://img1.wikia.nocookie.net/__cb20101219155130/uncyclopedia/images/7/70/Facebooklogin.png
Run Code Online (Sandbox Code Playgroud)

Cha*_*lie 109

只要 您可以使用下面的方法.

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

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

如果您不知道Image的格式(.png,.jpeg等)

public void SaveImage(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();
}
Run Code Online (Sandbox Code Playgroud)

使用它

try
{
    SaveImage("--- 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
}

Run Code Online (Sandbox Code Playgroud)

  • @Arsman Ahmad这是一个完全不同的问题,应该在别处寻找或询问.该线程用于下载单个图像. (4认同)

Per*_*t28 68

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

知道图像格式,将图像下载到文件中

using (WebClient webClient = new WebClient()) 
{
   webClient.DownloadFile("http://yoururl.com/image.png", "image.png") ; 
}
Run Code Online (Sandbox Code Playgroud)

在不知道图像格式的情况下将图像下载到文件中

您可以使用Image.FromStream加载任何类型的常用位图(jpg,png,bmp,gif,...),它会自动检测文件类型,你甚至不需要检查url扩展名(这不是很好实践).例如:

using (WebClient webClient = new WebClient()) 
{
    byte [] data = webClient.DownloadData("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_110e04e71d9");

   using (MemoryStream mem = new MemoryStream(data)) 
   {
       using (var yourImage = Image.FromStream(mem)) 
       { 
          // If you want it as Png
           yourImage.Save("path_to_your_file.png", ImageFormat.Png) ; 

          // If you want it as Jpeg
           yourImage.Save("path_to_your_file.jpg", ImageFormat.Jpeg) ; 
       }
   } 

}
Run Code Online (Sandbox Code Playgroud)

注意:Image.FromStream如果下载的内容不是已知的图像类型,则可能引发ArgumentException .

在MSDN上查看此参考以查找所有可用格式.这是参考WebClientBitmap.

  • 请注意,您需要"使用System.Drawing;" for Image.FromStream() (2认同)
  • 请注意,除了要求成像库检测图像格式之外,您还可以查看响应标头,以查看源使用WebClient.ResponseHeaders [“ Content-Type”]认为图像的格式。 (2认同)

Mar*_*ter 26

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

  • 他们使用Imagefrom System.Drawing(不适用于 .NET Core)来查找图像格式
  • 他们使用System.Net.WebClient弃用的

我们不建议您将该WebClient类用于新的开发。而是使用System.Net.Http.HttpClient类。

.NET Core 异步解决方案

获取文件扩展名

获取文件扩展名的第一部分是从 URL 中删除所有不必要的部分。我们可以使用Uri.GetLeftPart()和 UriPartial.Path 来获取从Schemeup 到Path.
换句话说,https://www.example.com/image.png?query&with.dots变成https://www.example.com/image.png

之后,我们可以使用Path.GetExtension()仅获取扩展名(在我之前的示例中,.png)。

var uriWithoutQuery = uri.GetLeftPart(UriPartial.Path);
var fileExtension = Path.GetExtension(uriWithoutQuery);
Run Code Online (Sandbox Code Playgroud)

下载图像

从这里开始应该是直截了当的。使用HttpClient.GetByteArrayAsync下载图像,创建路径,确保目录存在,然后使用File.WriteAllBytesAsync()将字节写入路径

private async Task DownloadImageAsync(string directoryPath, string fileName, Uri uri)
{
    using var httpClient = new HttpClient();

    // Get the file extension
    var uriWithoutQuery = uri.GetLeftPart(UriPartial.Path);
    var fileExtension = Path.GetExtension(uriWithoutQuery);

    // Create file path and ensure directory exists
    var path = Path.Combine(directoryPath, $"{fileName}{fileExtension}");
    Directory.CreateDirectory(directoryPath);

    // Download the image and write to the file
    var imageBytes = await httpClient.GetByteArrayAsync(uri);
    await File.WriteAllBytesAsync(path, imageBytes);
}
Run Code Online (Sandbox Code Playgroud)

请注意,您需要以下 using 指令。

using System;
using System.IO;
using System.Threading.Tasks;
using System.Net.Http;
Run Code Online (Sandbox Code Playgroud)

示例用法

var folder = "images";
var fileName = "test";
var url = "https://cdn.discordapp.com/attachments/458291463663386646/592779619212460054/Screenshot_20190624-201411.jpg?query&with.dots";

await DownloadImageAsync(folder, fileName, new Uri(url));
Run Code Online (Sandbox Code Playgroud)

笔记

  • HttpClient为每个方法调用创建一个新方法是不好的做法。它应该在整个应用程序中重复使用。我写了一个简短的示例ImageDownloader(50 行),其中包含更多文档,可以正确重用HttpClient并正确处置它,您可以在此处找到。

  • 这应该是 2022 年公认的答案。 (2认同)

Bri*_*yer 12

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

Image DownloadImage(string fromUrl)
{
    using (System.Net.WebClient webClient = new System.Net.WebClient())
    {
        using (Stream stream = webClient.OpenRead(fromUrl))
        {
            return Image.FromStream(stream);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Ali*_*yun 6

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

并在Laod Complete Event中保存图像

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

void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e) {
   pictureBox1.Image.Save(destination); }
Run Code Online (Sandbox Code Playgroud)


Cha*_*mar 6

试试这个它对我有用

在你的控制器中写这个

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));
        }
Run Code Online (Sandbox Code Playgroud)

这是我的观点

<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
Run Code Online (Sandbox Code Playgroud)