我有一个透明的 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/