You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET WPF中Button显示带透明区域PNG出现异常求助

WPF按钮显示带透明PNG异常的解决方案

我在WPF的Button中展示带透明区域的PNG图片时,遇到了透明区域被错误填充/重复像素的异常问题。

用到的XAML代码

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

问题根源

问题出在Bitmap转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;
}

BMP格式本身不支持透明通道,原本PNG的透明信息在转存为BMP时完全丢失,这才导致显示时透明区域出现异常像素填充。

修复方案

将转换时的保存格式改为PNG,同时优化流的生命周期管理:

public static BitmapImage Convert(Bitmap src)
{
    using (MemoryStream ms = new MemoryStream())
    {
        src.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        BitmapImage image = new BitmapImage();
        image.BeginInit();
        ms.Seek(0, SeekOrigin.Begin);
        image.StreamSource = ms;
        image.CacheOption = BitmapCacheOption.OnLoad; // 确保流关闭后图片仍能正常显示
        image.EndInit();
        return image;
    }
}

额外可以给Image添加渲染优化,避免缩放时的像素失真:

<Image Width="1cm" Height="1cm" x:Name="LogoImageChangeButton_Image"
       RenderOptions.BitmapScalingMode="HighQuality"/>

更高效的替代方案

如果图片是项目嵌入资源,可直接通过Uri加载BitmapImage,跳过System.Drawing.Bitmap的转换步骤,彻底避免格式兼容问题:

LogoImageChangeButton_Image.Source = new BitmapImage(new Uri("pack://application:,,,/你的程序集名称;component/Resources/ChangeImageIcon.png"));

内容的提问来源于stack exchange,提问作者julian bechtold

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 11:40:13