From PNG to BitmapImage. Transparency issue.
.net, c#, wpf
Solution
Ria's answer helped me resolve the transparency problem. Here's the code that works for me:
public BitmapImage ToBitmapImage(Bitmap bitmap)
{
using (MemoryStream stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Png); // Was .Bmp, but this did not show a transparent background.
stream.Position = 0;
BitmapImage result = new BitmapImage();
result.BeginInit();
// According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed."
// Force the bitmap to load right now so we can dispose the stream.
result.CacheOption = BitmapCacheOption.OnLoad;
result.StreamSource = stream;
result.EndInit();
result.Freeze();
return result;
}
}
Problem
I've got some issue. I'm trying to load png-image from resources to BitmapImage propery in my viewModel like this: ``` Bitmap bmp = Resource1.ResourceManager.GetObject(String.Format("_{0}",i)) as Bitmap; MemoryStream ms = new MemoryStream(); bmp.Save(ms, ImageFormat.Bmp); BitmapImage bImg = new BitmapImage(); bImg.BeginInit(); bImg.StreamSource = new MemoryStream(ms.ToArray()); bImg.EndInit(); this.Image = bImg; ``` But when I do it, I lose the transparency of the image. So the question is how can I load png image from resources without loss of transparency? Thanks, Pavel.