c# - 将位图转换为 ImageSource 后资源 png 质量下降

标签 c# wpf

我有一个透明的 PNG,当我将其转换为 ImageSource 时,质量会下降很多。我所做的转换如下:

public static ImageSource ToImageSource()
    {   Bitmap bitmap = Properties.Resources.Image;
        IntPtr hBitmap = bitmap.GetHbitmap();

        ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap(
            hBitmap,
            IntPtr.Zero,
            Int32Rect.Empty,
            BitmapSizeOptions.FromEmptyOptions());
        RenderOptions.SetBitmapScalingMode(wpfBitmap, BitmapScalingMode.HighQuality);

        return wpfBitmap;
    }

但是质量真的很差。当我直接调用计算机上的文件时,质量是正确的:

<DataGridTemplateColumn Width="14" IsReadOnly="True">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Image Source="C:\Users\MyUser\Desktop\Image.png" Width="14" Height="14"></Image>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

是否有另一种方法可以在不损失质量和透明度的情况下转换资源?

最佳答案

遗憾的是我无法测试您的代码,但我认为您必须将模式设置为最近邻

试试这个

public static ImageSource ToImageSource()
{   
   Bitmap bitmap = Properties.Resources.Image;
   IntPtr hBitmap = bitmap.GetHbitmap();

   ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap(
       hBitmap,
       IntPtr.Zero,
       Int32Rect.Empty,
       BitmapSizeOptions.FromEmptyOptions());
   RenderOptions.SetBitmapScalingMode(wpfBitmap, BitmapScalingMode.NearestNeighbor);

   return wpfBitmap;
}

关于c# - 将位图转换为 ImageSource 后资源 png 质量下降,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56700995/

相关文章:

c# - Hangfire:打开的连接太多

c# - 为什么 .NET Math.Round 方法在处理负值时四舍五入而不是四舍五入?

c# - Linq:从两个不同的列表中找到相似的对象

c# - 让 SortDescription 对字符串进行不同的排序

c# - WPF:一排长度相等的 ToggleButtons?

c# - WPF 自定义基窗口类和样式

c# - 如何将 MailMesage 保存到 .msg 文件?

c# - ListboxItem 不同状态之间的动画

c# - WPF TreeView 和虚拟化(UI 和数据)

asp.net - 将 WPF 转换为 Web