Reputation: 6288
I am using a viewmodel bound to an image property on the UI and the viewmodel contains an ImageSource property. I set that property using the following function
private BitmapImage GetImageFromUri(Uri urisource)
{
if (urisource == null)
return null;
var image = new BitmapImage();
image.BeginInit();
image.UriSource = urisource;
image.EndInit();
image.Freeze(); //commenting this shows the image if the routine is called from the proper thread.
return image;
}
For some odd reason, in the following code, when I call Freeze on my BitmapImage, it does not appear on the main window.I get no exception or crash. Can anybody help me with this? I am setting the image property asynchronously so I need to be able to use the created image, assuming the GetImageFromUri call was made from a thread other than the UI thread.
Upvotes: 0
Views: 3378
Reputation: 345
IF i use StreamSource
, for me is enough:
public static BitmapSource ToBitmap(this MemoryStream stream)
{
try
{
using (stream)
{
stream.Position = 0;
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = stream;
image.EndInit();
image.Freeze();
return image;
}
}
catch (Exception)
{
return null;
}
}
But if i use UriSource
i need:
public static async Task<BitmapSource> ToBitmapAsync(this string sourceUri)
{
try
{
using (var client = new WebClient())
using (var stream = await client.OpenReadTaskAsync(new Uri(sourceUri)))
using (var ms = new MemoryStream())
{
stream.CopyTo(ms);
return ms.ToBitmap();
}
}
catch (Exception)
{
return null;
}
}
BitmapSource
has UriSource
, but it works after xaml rendered
Upvotes: 0
Reputation: 81253
Try setting the CacheOption for BitmapImage before freezing it. See if this works -
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = urisource;
image.EndInit();
image.Freeze();
Upvotes: 3
Reputation: 16628
Before you freeze it, you need to fully render it.
You should try to listen to the SourceUpdated event, and only then freeze the image.
On a side note, if you ever want to modify the Image after that, you will have to Clone it.
Upvotes: 1