异步将图像从Url加载到PictureBox

时间:2016-06-11 12:48:57

标签: c# .net winforms picturebox webrequest

我想在Windows窗体应用程序中从Web加载图像, 一切都很好,代码工作正常,但问题是应用程序停止工作,直到加载完成。 我希望看到并使用应用而无需等待加载

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

2 个答案:

答案 0 :(得分:5)

以下是解决方案:

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

以下是如何调用上述解决方案:

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

答案 1 :(得分:5)

PictureBox控件具有内置支持,可以异步加载图像。您不需要使用BackgroundWorker或async / await。它还可以从URL加载图像,因此您不需要使用Web请求。

您只需使用PictureBox方法或false的{​​{3}}属性即可。 LoadAsync属性的值应为pictureBox1.LoadAsync("https://i.stack.imgur.com/K4tAc.jpg"); ,这是默认值。

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

它相当于:

12 333  5
1 1234 14
20988 432
145677 34
78 954 34
9087 4 51