将图片从网址异步加载到PictureBox [英] Asynchronously Load an Image from a Url to a PictureBox

查看:114
本文介绍了将图片从网址异步加载到PictureBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Windows窗体应用程序上的网络加载图像, 一切都很好,代码可以正常工作,但是问题是应用程序停止工作,直到加载完成. 我想查看并使用应用程序而无需等待加载.

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

推荐答案

以下是解决方法:

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

这篇关于将图片从网址异步加载到PictureBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆