Button with transparent png image in .Net WPF

Advertisements

I have a WPF Button which should be displayed with a png image which has transparent areas.

This is my xaml code, which works for displaying an image:

<Button HorizontalAlignment="Left" VerticalAlignment="Top" Panel.ZIndex="2" Background="Transparent" BorderBrush="Transparent">
    <Image Width="1cm" Height="1cm" x:Name="LogoImageChangeButton_Image"/>
</Button>

This is the image. As you can see, it has transparent areas:

Unfortunately, wpf seems to repeat or assume pixels in the transparent areas for some unknown reason. Unfortunately, the effect looks quite glitchy so I cant describe it any better:

I have tried around with different stretch modes, all seemed to have this issue. Any help is appreciated.

This is how I set the image:

LogoImageChangeButton_Image.Source = BitmapHelper_Net.BitmapConverter.Convert(Properties.Resources.ChangeImageIcon);

and this is how I convert the bitmap to an imagesource:

public static BitmapImage Convert(Bitmap src)
{
    MemoryStream ms = new MemoryStream();
    ((System.Drawing.Bitmap)src).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;
}

>Solution :

Do not use BMP as conversion format. It does not support transparency.

Use PNG, and set BitmapCacheOption.OnLoad to be able to dispose of the stream after EndInit.

public static BitmapImage Convert(Bitmap src)
{
    var image = new BitmapImage();

    using (var memoryStream ms = new MemoryStream())
    {
        src.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        ms.Seek(0, SeekOrigin.Begin);

        image.BeginInit();
        image.StreamSource = ms;
        image.CacheOption = BitmapCacheOption.OnLoad;
        image.EndInit();
    }

    return image;
}

Leave a Reply Cancel reply