teocomi

ValueConverter URL to Image

Jul 21st, 2014
1,707
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.20 KB | None | 0 0
  1. [ValueConversion(typeof(String), typeof(BitmapImage))]
  2.     public class UriToImageConv : IValueConverter
  3.     {
  4.  
  5.         public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  6.         {
  7.             if (value == null || value.ToString() == "")
  8.                 return null;
  9.  
  10.             RestClient client = new RestClient();
  11.             var request = new RestRequest(value.ToString(), Method.GET);
  12.             try
  13.             {
  14.                 string username = MySettings.Get("username");
  15.                 string password = DataProtector.DecryptData(MySettings.Get("password"));
  16.  
  17.                 if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
  18.                     return null;
  19.  
  20.                 HttpBasicAuthenticator user = new HttpBasicAuthenticator(username, password);
  21.                 client.Authenticator = user;
  22.                
  23.                 var response = client.Execute(request);
  24.                 return LoadImage(response.RawBytes);
  25.  
  26.  
  27.             }
  28.             catch (Exception ex1)
  29.             {
  30.                 MessageBox.Show("exception: " + ex1);
  31.             }
  32.  
  33.             return null;
  34.  
  35.  
  36.         }
  37.         public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  38.         {
  39.  
  40.             throw new NotImplementedException();
  41.         }
  42.  
  43.  
  44.         private static BitmapImage LoadImage(byte[] imageData)
  45.         {
  46.            
  47.             try
  48.             {
  49.                 if (imageData == null || imageData.Length == 0) return null;
  50.                 var image = new BitmapImage();
  51.                 using (var mem = new MemoryStream(imageData))
  52.                 {
  53.                     mem.Position = 0;
  54.                     image.BeginInit();
  55.                     image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
  56.                     image.CacheOption = BitmapCacheOption.OnLoad;
  57.                     image.UriSource = null;
  58.                     image.StreamSource = mem;
  59.                     image.EndInit();
  60.                 }
  61.                 image.Freeze();
  62.                 return image;
  63.             }
  64.             catch { }
  65.             return null;
  66.  
  67.         }
  68.  
  69.     }
Advertisement
Add Comment
Please, Sign In to add comment