Synchronously download an image from URL

后端 未结 4 2026
离开以前
离开以前 2020-12-24 10:18

I just want to get a BitmapImage from a internet URL, but my function doesn\'t seem to work properly, it only return me a small part of the image. I know WebResponse is work

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-24 10:43

    First you should just download the image, and store it locally in a temporary file or in a MemoryStream. And then create the BitmapImage object from it.

    You can download the image for example like this:

    Uri urlUri = new Uri(url); 
    var request = WebRequest.CreateDefault(urlUri);
    
    byte[] buffer = new byte[4096];
    
    using (var target = new FileStream(targetFileName, FileMode.Create, FileAccess.Write))
    {
        using (var response = request.GetResponse())
        {    
            using (var stream = response.GetResponseStream())
            {
                int read;
    
                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    target.Write(buffer, 0, read);
                }
            }
        }
    }
    

提交回复
热议问题