我使用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.