Resource png loses quality after convert bitmap to ImageSource

Viewed 232

I have a PNG with transparency that loses a lot of quality when I convert it to ImageSource. What I do to convert it is the following:

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;
    }

But the quality is really bad. when I call directly to the file on my computer the quality is correct:

<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>

Is there another way to transform the resource without losing quality and transparency?

3 Answers

Sadly i can not test your code but i think you have to set the Mode to NearestNeighbor

Try this

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;
}

Or... try this :)

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);

Calling DeleteObject will release the GDI handle.

Try This:

BitmapImage image = new BitmapImage(new Uri("your image path here", UriKind.Relative));

Edit: Assuming you have the image path.

Related