Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [ValueConversion(typeof(String), typeof(BitmapImage))]
- public class UriToImageConv : IValueConverter
- {
- public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
- {
- if (value == null || value.ToString() == "")
- return null;
- RestClient client = new RestClient();
- var request = new RestRequest(value.ToString(), Method.GET);
- try
- {
- string username = MySettings.Get("username");
- string password = DataProtector.DecryptData(MySettings.Get("password"));
- if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
- return null;
- HttpBasicAuthenticator user = new HttpBasicAuthenticator(username, password);
- client.Authenticator = user;
- var response = client.Execute(request);
- return LoadImage(response.RawBytes);
- }
- catch (Exception ex1)
- {
- MessageBox.Show("exception: " + ex1);
- }
- return null;
- }
- public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
- {
- throw new NotImplementedException();
- }
- private static BitmapImage LoadImage(byte[] imageData)
- {
- try
- {
- if (imageData == null || imageData.Length == 0) return null;
- var image = new BitmapImage();
- using (var mem = new MemoryStream(imageData))
- {
- mem.Position = 0;
- image.BeginInit();
- image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
- image.CacheOption = BitmapCacheOption.OnLoad;
- image.UriSource = null;
- image.StreamSource = mem;
- image.EndInit();
- }
- image.Freeze();
- return image;
- }
- catch { }
- return null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment