如何使用winforms从网上下载显示下载进度的图像?

前端之家收集整理的这篇文章主要介绍了如何使用winforms从网上下载显示下载进度的图像?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用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,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,bytesRead,writeResult =>
    {
      readState.AccumulatedResponse.EndWrite(writeResult);
      readState.Response.BeginRead(readState.Buffer,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具有一种称为“渐进式JPEG”的特殊编码模式,其中数据在逐步更高细节的多次传递中被压缩. Windows 7为此拥有 built-in support.

猜你在找的C#相关文章