且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从url下载图像使用c#

更新时间:2023-11-26 20:00:34

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

Simply You can use following methods.

  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 )。他们将文件存储在Directory中,而不是C#字符串,URI中不需要格式扩展名。

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



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

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



使用它



Using it

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
 }