locked
为什么下载的图片经常会数据错误? RRS feed

  • 问题

  • 我的应用里面会下载图片。但是经常会遇到一些图片下载完以后无法正常显示。后面调试了一下,发现收到的图片数据不正确。

    但是服务器上的图片本身是正常的。通过电脑的浏览器打开也都是正常的。这个是什么原因引起的?是不是应用进行请求的时候,还需要进行一些HTTP头设置之类的?

            private void DownloadFile(string url)
            {
                ShowProgressOverlay();
                HttpWebRequest DownLoadReq = WebRequest.Create(new Uri(url)) as HttpWebRequest;
                IAsyncResult result = DownLoadReq.BeginGetResponse(DownloadFileCallback, DownLoadReq);
            }
    
            private void DownloadFileCallback(IAsyncResult result)
            {
                try
                {
                    HttpWebRequest request = (HttpWebRequest)(result.AsyncState);
                    HttpWebResponse response = request.EndGetResponse(result) as HttpWebResponse;
                    long dataLen = response.ContentLength;
                    Stream responseStream = response.GetResponseStream();
                    BinaryReader streamReader = new BinaryReader(responseStream);
                    string savePath = Modules.GetLocalPath(PhotoList[CurPhotoIndex]);
                    using (IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (myStore.FileExists(savePath))
                        {
                            myStore.DeleteFile(savePath);
                        }
    
                        try
                        {
                            IsolatedStorageFileStream fs = myStore.OpenFile(savePath, FileMode.Create, FileAccess.ReadWrite);
                            long downloadSize = 0;
                            byte[] readBuffer = new byte[1024];
                            int iReadBytes = 0;
    
                            do
                            {
                                iReadBytes = streamReader.Read(readBuffer, 0, readBuffer.Length);
    
                                if (iReadBytes > 0)
                                {
                                    fs.Write(readBuffer, 0, iReadBytes);
                                    downloadSize += iReadBytes;
                                }
                            } while (downloadSize < response.ContentLength);
                            fs.Flush();
                            fs.Close();
                            Dispatcher.BeginInvoke(() =>
                            {
                                HideProgressOverlay();
                                LoadPhoto();
                            });
                        }
                        catch (Exception ex)
                        {
                            Dispatcher.BeginInvoke(() =>
                            {
                                HideProgressOverlay();
                                MessageBox.Show(ex.Message);
                            });
                        }
                    }
                }
                catch (Exception ex)
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        HideProgressOverlay();
                        MessageBox.Show(ex.ToString());
                    });
                }
            }

    2015年1月20日 10:03

答案

  • 你尝试下System.Net.Http.HttpClient:

    private IEnumerable<string> CountPictures(int from, int to, string folder)
    {
        for (int i = from; i < to; i++)
            yield return string.Format("{0}/image{1}.jpg", folder, i.ToString("D2"));
    }
    
    private async Task ImportImages()
    {
        HttpClient c = new HttpClient();
        int count = 0;
        c.BaseAddress = new Uri("http://www.cs.washington.edu/research/imagedatabase/groundtruth/", UriKind.Absolute);
        foreach (var pic in CountPictures(1, 48, "leaflesstrees"))
        {
            var pic_response = await c.GetAsync(pic, HttpCompletionOption.ResponseContentRead);
            if (pic_response.IsSuccessStatusCode)
            {
                await SaveImageAsync(pic.Replace('/', '_'), await pic_response.Content.ReadAsStreamAsync());
                Debug.WriteLine(pic + " imported");
                count++;
            }
        }           
        Debug.WriteLine(string.Format("{0} images imported", count));
    }
    
    private Task SaveImageAsync(string filename, Stream stream)
    {
        var task = Task.Factory.StartNew(() =>
        {
            if (stream == null || filename == null)
            {
                throw new ArgumentException("one of parameters is null");
            }
            try
            {
                using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (IsolatedStorageFileStream targetStream = isoStore.OpenFile(filename, FileMode.Create, FileAccess.Write))
                    {
                        byte[] readBuffer = new byte[4096];
                        int bytesRead = -1;
                        stream.Position = 0;
                        targetStream.Position = 0;
    
                        while ((bytesRead = stream.Read(readBuffer, 0, readBuffer.Length)) > 0)
                        {
                            targetStream.Write(readBuffer, 0, bytesRead);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("DocumentStorageService::LoadImage FAILED " + e.Message);
            }
        });
        return task;
    }

    2015年1月21日 9:36