3

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.

korovaisdead
  • 6,271
  • 4
  • 26
  • 33
  • 1
    @Felice Pollano: you should restore your deleted answer, which was good. Saving the image as a .bmp file and loading it will obviously lose the transparency. – Julien Lebosquain Jul 18 '12 at 08:06

4 Answers4

8

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;
  }
}
Dean
  • 731
  • 8
  • 21
4

It's because the BMP file format doesn't support transparency while the PNG file format does. If you want transparency you are going to have to use PNG.

Try ImageFormat.Png for saving.

Ria
  • 10,237
  • 3
  • 33
  • 60
0

This is usually caused by 64-bit depth PNG images, which BitmapImage doesn't support. Photoshop seems to incorrectly display these as 16-bit, so you need to check with Windows Explorer:

  • Right click the file.
  • Click Properties.
  • Go to the Details tab.
  • Look for "Bit depth" - it's usually in the Image section, with width and height.

If it says 64, you need to re-encode the image with 16-bit depth. I suggest using Paint.NET, since it properly handles PNG bit depths.

Polynomial
  • 27,674
  • 12
  • 80
  • 107
0

I viewed this post to find answers to the same transparancy problem as here.

But then I saw the sample code given, and just wanted to share this code to load Image from Resources.

Image connection = Resources.connection;

Using this I found that I need not recode my images to 16 bit. Thanks.