6

インターネット URL から BitmapImage を取得したいだけですが、関数が正しく機能していないようで、画像のごく一部しか返されません。私は WebResponse が非同期で動作していることを知っています。それが確かにこの問題を抱えている理由ですが、どうすれば同期的に行うことができますか?

    internal static BitmapImage GetImageFromUrl(string url)
    {
        Uri urlUri = new Uri(url);
        WebRequest webRequest = WebRequest.CreateDefault(urlUri);
        webRequest.ContentType = "image/jpeg";
        WebResponse webResponse = webRequest.GetResponse();

        BitmapImage image = new BitmapImage();
        image.BeginInit();
        image.StreamSource = webResponse.GetResponseStream();
        image.EndInit();

        return image;
    }
4

4 に答える 4

10

まず、画像をダウンロードして、一時ファイルまたはにローカルに保存する必要がありMemoryStreamます。そして、そこBitmapImageからオブジェクトを作成します。

たとえば、次のように画像をダウンロードできます。

Uri urlUri = new Uri(url); 
var request = WebRequest.CreateDefault(urlUri);

byte[] buffer = new byte[4096];

using (var target = new FileStream(targetFileName, FileMode.Create, FileAccess.Write))
{
    using (var response = request.GetResponse())
    {    
        using (var stream = response.GetResponseStream())
        {
            int read;

            while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                target.Write(buffer, 0, read);
            }
        }
    }
}
于 2010-09-07T14:37:36.857 に答える
2

なぜ使用しないのSystem.Net.WebClient.DownloadFileですか?

string url = @"http://www.google.ru/images/srpr/logo3w.png";
string file = System.IO.Path.GetFileName(url);
System.Net.WebClient cln = new System.Net.WebClient();
cln.DownloadFile(url,file);
于 2012-11-07T16:56:11.113 に答える
0

これは、URLから画像を取得するために使用するコードです。

   // get a stream of the image from the webclient
    using ( Stream stream = webClient.OpenRead( imgeUri ) ) 
    {
      // make a new bmp using the stream
       using ( Bitmap bitmap = new Bitmap( stream ) )
       {
          //flush and close the stream
          stream.Flush( );
          stream.Close( );
          // write the bmp out to disk
          bitmap.Save( saveto );
       }
    }
于 2010-09-07T14:40:30.553 に答える
-3

最も簡単なのは

Uri pictureUri = new Uri(pictureUrl);
BitmapImage image = new BitmapImage(pictureUri);

その後、BitmapCacheOption を変更して取得プロセスを開始できます。ただし、画像は非同期で取得されます。でもあまり気にしなくていい

于 2013-05-05T18:55:43.010 に答える