gpt4 book ai didi

c# - 如何使用 winforms 从 Web 下载显示下载进度的图像?

转载 作者:太空狗 更新时间:2023-10-29 18:08:02 24 4
gpt4 key购买 nike

我以这种方式使用 WebRequest 从 URL 异步下载图像:

public void Download(string url)
{
byte[] buffer = new byte[0x1000];
WebRequest request = HttpWebRequest.Create(url);
request.Method = "GET";
request.ContentType = "image/gif";

request.BeginGetResponse(result =>
{
WebRequest webRequest = result.AsyncState as WebRequest;

WebResponse response = webRequest.EndGetResponse(result);
ReadState readState = new ReadState()
{
Response = response.GetResponseStream(),
AccumulatedResponse = new MemoryStream(),
Buffer = buffer,
};

readState.Response.BeginRead(buffer, 0,
readState.Buffer.Length, ReadCallback, readState);
}, request);
}

public void ReadCallback(IAsyncResult result)
{
ReadState readState = result.AsyncState as ReadState;
int bytesRead = readState.Response.EndRead(result);
if(bytesRead > 0)
{
readState.AccumulatedResponse.BeginWrite(readState.Buffer, 0, bytesRead, writeResult =>
{
readState.AccumulatedResponse.EndWrite(writeResult);
readState.Response.BeginRead(readState.Buffer, 0, readState.Buffer.Length, ReadCallback, readState);
}, null);
}
else
{
readState.AccumulatedResponse.Flush();
readState.Response.Close();
pictureBox1.Image = Image.FromStream(readState.AccumulatedResponse);
}
}

public class ReadState
{
public Stream Response { get; set; }
public Stream AccumulatedResponse { get; set; }
public byte[] Buffer { get; set; }
}

它工作正常,但我想像浏览器一样显示下载进度,而不是仅在完成时显示。

如果我这样做

pictureBox1.Image = Image.FromStream(readState.AccumulatedResponse);

在它完成之前我得到一个异常,该图片无效,即使它有一些数据。反正有显示部分数据吗?

最佳答案

JPEG 有一种称为“Progressive JPEG”的特殊编码模式,在这种模式下,数据被多次压缩,细节逐渐增加。 Windows 7 有 built-in support为此。

关于c# - 如何使用 winforms 从 Web 下载显示下载进度的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/792544/

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