我有一个透明度的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:UsersMyUserDesktopImage.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;
}
或者试试这个:)
public static ImageSource ToImageSource()
{
Bitmap bitmap = Properties.Resources.Image;
IntPtr hBitmap = bitmap.GetHbitmap();
ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
new Int32Rect(0, 0, bitmap.Width, bitmap.Height),
BitmapSizeOptions.FromEmptyOptions());
DeleteObject(hBitmap);
return wpfBitmap;
}
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
调用DeleteObject
将释放 GDI 句柄。
试试这个:
BitmapImage image = new BitmapImage(new Uri("your image path here", UriKind.Relative));
编辑:假设您有图像路径。