سؤال

أرغب فقط في الحصول على نقطية من عنوان URL على الإنترنت ، لكن وظيفتي لا يبدو أنها تعمل بشكل صحيح ، إنها تعيد لي جزءًا صغيرًا من الصورة فقط. أعلم أن 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;
    }
هل كانت مفيدة؟

المحلول

أولاً ، يجب عليك فقط تنزيل الصورة ، وتخزينها محليًا في ملف مؤقت أو في 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);
            }
        }
    }
}

نصائح أخرى

لماذا لا تستخدم 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);

هذا هو الرمز الذي أستخدمه للاستيلاء على صورة من عنوان 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 );
       }
    }

أبسط

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

يمكنك بعد ذلك تغيير BitmapCacheOption لبدء عملية الاسترجاع. ومع ذلك ، يتم استرداد الصورة في Async. لكن يجب ألا تهتم كثيرا

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top