Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Button with transparent png image in .Net WPF

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:
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:
enter image description here

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading