0

This is my code:

<Image>
    <Image.Source>
        <Binding Source="{x:Static properties:Resources.myLogo}" Converter="{StaticResource BitmapToImageSourceConverter}" />
    </Image.Source>
</Image>

And the BitmapToImageSourceConverter's Convert method is this one:

public object Convert(object value, Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
    {
        MemoryStream ms = new MemoryStream();
        ((System.Drawing.Bitmap)value).Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
        BitmapImage image = new BitmapImage();
        image.BeginInit();
        ms.Seek(0, SeekOrigin.Begin);
        image.StreamSource = ms;
        image.EndInit();

        return image;
    }

The image is shown just like it should, but with black background. I tried to fix it like this:

<StackPanel Width="230" Height="80" Grid.Column="0" Margin="85 -40 0 0" HorizontalAlignment="Left" VerticalAlignment="Bottom" Background="Transparent">
    <Image>
        <Image.Source>
            <Binding Source="{x:Static properties:Resources.myLogo}" Converter="{StaticResource BitmapToImageSourceConverter}" />
        </Image.Source>
    </Image>
</StackPanel>

How can I fix the black background?

petko_stankoski
  • 10,459
  • 41
  • 127
  • 231

1 Answers1

7

I fixed it using @Dean's answer here: From PNG to BitmapImage. Transparency issue.

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;
  }
}
Community
  • 1
  • 1
petko_stankoski
  • 10,459
  • 41
  • 127
  • 231