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

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

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


慕容708150
浏览 155回答 3
3回答

红颜莎娜

或者...试试这个 :)public static ImageSource ToImageSource(){&nbsp; &nbsp; &nbsp;Bitmap bitmap = Properties.Resources.Image;&nbsp; &nbsp; &nbsp;IntPtr hBitmap = bitmap.GetHbitmap();&nbsp; &nbsp; &nbsp;ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hBitmap,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; IntPtr.Zero,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new Int32Rect(0, 0, bitmap.Width, bitmap.Height),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; BitmapSizeOptions.FromEmptyOptions());&nbsp; &nbsp; &nbsp; DeleteObject(hBitmap);&nbsp; &nbsp; &nbsp; return wpfBitmap;}[System.Runtime.InteropServices.DllImport("gdi32.dll")]public static extern bool DeleteObject(IntPtr hObject);调用DeleteObject将释放 GDI 句柄。

慕妹3146593

遗憾的是我无法测试您的代码,但我认为您必须将模式设置为 NearestNeighbor尝试这个public static ImageSource ToImageSource(){&nbsp; &nbsp;&nbsp; &nbsp;Bitmap bitmap = Properties.Resources.Image;&nbsp; &nbsp;IntPtr hBitmap = bitmap.GetHbitmap();&nbsp; &nbsp;ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap(&nbsp; &nbsp; &nbsp; &nbsp;hBitmap,&nbsp; &nbsp; &nbsp; &nbsp;IntPtr.Zero,&nbsp; &nbsp; &nbsp; &nbsp;Int32Rect.Empty,&nbsp; &nbsp; &nbsp; &nbsp;BitmapSizeOptions.FromEmptyOptions());&nbsp; &nbsp;RenderOptions.SetBitmapScalingMode(wpfBitmap, BitmapScalingMode.NearestNeighbor);&nbsp; &nbsp;return wpfBitmap;}

回首忆惘然

尝试这个:BitmapImage&nbsp;image&nbsp;=&nbsp;new&nbsp;BitmapImage(new&nbsp;Uri("your&nbsp;image&nbsp;path&nbsp;here",&nbsp;UriKind.Relative));编辑:假设您有图像路径。
打开App,查看更多内容
随时随地看视频慕课网APP