Asynchronously Load an Image from a Url to a PictureBox

旧时模样 提交于 2019-11-28 05:31:32

问题


I want to load image from the web on windows forms application, Everything is good and code works fine, but the problem is the app stop working until the loading goes to finish. I want to see and work with app without waiting to loading .

PictureBox img = new System.Windows.Forms.PictureBox();
var request = WebRequest.Create(ThumbnailUrl);

using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
    img.Image = Bitmap.FromStream(stream);
}

回答1:


Here is the solution:

public async Task<Image> GetImageAsync(string url)
{
    var tcs = new TaskCompletionSource<Image>();
    Image webImage = null;
    HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
    request.Method = "GET";
    await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null)
        .ContinueWith(task =>
        {
            var webResponse = (HttpWebResponse) task.Result;
            Stream responseStream = webResponse.GetResponseStream();
            if (webResponse.ContentEncoding.ToLower().Contains("gzip"))
                responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
            else if (webResponse.ContentEncoding.ToLower().Contains("deflate"))
                responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);

            if (responseStream != null) webImage = Image.FromStream(responseStream);
            tcs.TrySetResult(webImage);
            webResponse.Close();
            responseStream.Close();
        });
    return tcs.Task.Result;
}

Here is how to call the above solution:

PictureBox img = new System.Windows.Forms.PictureBox();
var result = GetImageAsync(ThumbnailUrl);
result.ContinueWith(task =>
{
    img.Image = task.Result;
});



回答2:


PictureBox control has built-in support for loading images asynchronously. You don't need to use BackgroundWorker or async/await. It also can load an image from a URL, so you don't need to use a web request.

You can simply use the LoadAsync method or ImageLocation property of PictureBox. The value of WaitOnLoad property should be false, which is the default.

pictureBox1.LoadAsync("https://i.stack.imgur.com/K4tAc.jpg");

It's equivalent to:

pictureBox1.ImageLocation = "https://i.stack.imgur.com/K4tAc.jpg";


来源:https://stackoverflow.com/questions/37763916/asynchronously-load-an-image-from-a-url-to-a-picturebox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!