gpt4 book ai didi

c# - 将图像从 Url 异步加载到 PictureBox

转载 作者:行者123 更新时间:2023-11-30 13:21:48 24 4
gpt4 key购买 nike

我想在 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);
}

最佳答案

解决方法如下:

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

关于c# - 将图像从 Url 异步加载到 PictureBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37763916/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com