本文介绍了如何下载网页显示使用的WinForms下载在C#中的进步的形象呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我异步使用的WebRequest这种方式从网址下载图片:

I download an image from an URL asynchronously using WebRequest this way:

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

和它的作品不错,但我想表明的进展下载的浏览器做的,而不是只显示当它完成。

and it works ok, but I would like to show the progress of the download as the browsers do, and not to show only when it finishes.

如果我

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



它完成我得到一个异常的画面是无效的,即使它有一些数据之前。
反正是有显示的部分数据?

before it finishes I get an exception that the picture is not valid, even though it has some data.Is there anyway to show partial data?

推荐答案

JPEG有所谓的渐进式JPEG的特殊编码模式,其中数据在逐渐升高的细节的多次通过压缩。 Windows 7已经此

JPEG has a special encoding mode called "Progressive JPEG" in which data is compressed in multiple passes of progressively higher detail. Windows 7 has built-in support for this.

这篇关于如何下载网页显示使用的WinForms下载在C#中的进步的形象呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 05:38