1

I'm using this method for converting a Bitmap to a BitmapImage I found on SO. It's not setting the Width and Height of the BitmapImage correctly.

private BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
{
    Console.WriteLine("Conversion Bitmap Size: {0}, {1}", bitmap.Width, bitmap.Height);
    using (MemoryStream memory = new MemoryStream())
    {
        bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
        memory.Position = 0;
        BitmapImage bitmapImage = new BitmapImage();
        bitmapImage.BeginInit();
        bitmapImage.StreamSource = memory;
        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapImage.EndInit();

        Console.WriteLine("Bitmap Size: {0}, {1}", bitmapImage.Width, bitmapImage.Height);

        return bitmapImage;
    }
}

When passing in a Bitmap with the size of 1920x350 I get the following output.

Conversion Bitmap Size: 1920, 350
Bitmap Size: 2559.67994453276, 466.608323222118

Does anyone know what's causing this and how to fix it?

GeoDoX
  • 21
  • 4
  • Check the bitmapImage's PixelWidth and PixelHeight. It only equals Width and Height for bitmaps with 96 dpi. – Clemens Jan 16 '20 at 18:00
  • @Clemens Worked like a charm. Should bitmaps usually be 96dpi? All images I create in Photoshop are generally 72dpi. – GeoDoX Jan 16 '20 at 18:18
  • 96 dpi is the native bitmap resolution in WPF, because 96 is the value of the frameworks's "device independent units" per inch. – Clemens Jan 16 '20 at 18:19
  • Just in case, you don't need the conversion from Bitmap to BitmapImage to load a bitmap from file. You can do that directly with BitmapImage. – Clemens Jan 16 '20 at 18:25
  • @Clemens My resources in my project are Bitmaps according to VS, so unfortunately it's necessary – GeoDoX Jan 20 '20 at 02:10
  • Not at all. You typically don't use Resources.resx in WPF. Even when you do, you may directly access the resource file by a WPF Resource File Pack URI. See here: https://stackoverflow.com/a/15008178/1136211, https://stackoverflow.com/a/22957974/1136211, https://stackoverflow.com/a/12693661/1136211. – Clemens Jan 20 '20 at 06:57
  • I wasn't aware of that! Haven't tried it but I have no doubts it'll work. – GeoDoX Jan 21 '20 at 16:48

0 Answers0