FirstStep FirstStep - 1 year ago 191
C# Question

Why this Bitmap Image changes its size after I load it?

Quick question:

I have this 1000 x 1000 bitmap image:

enter image description here

and I use this routine to load it:

private BitmapSource initialBitmap = new BitmapImage(new Uri("C:\\Users\\...\\Desktop\\Original.bmp"));

Why after I load it, and right after I step over the above line, I see it as 800 x 800?

enter image description here

P.S I want it to be 1000 x 1000 and without using any Resize functions. It was working and suddenly it is 800*800 !

Answer Source

The values returned by BitmapSource.Width and BitmapSource.Height are not in pixels, but rather WPF's device-independent units, which are always 96 dpi. E.g.:

Gets the width of the bitmap in device-independent units (1/96th inch per unit).

If you want to know the actual pixel width and height, you need to use the PixelWidth and PixelHeight properties.

Your question isn't very specific, but if what you are actually concerned about is having the bitmap display at the same size in which it was authored, then the easiest solution is to make sure you author it at 96 dpi. Whatever program you're using to author the bitmap likely has a place where you can set the bitmap resolution. Typically this can be set with or without changing the pixel dimensions of the image (i.e. scaling the image larger or smaller); you want to do it without scaling the image, so that the pixel dimensions remain the same but the dpi changes to match what WPF is using.

Note that this still won't guarantee the bitmap displays at a specific pixel size. The display resolution can be and often is different from 96 dpi, in which case WPF will scale images to ensure that the physical dimensions of the image (i.e. the dimensions in inches, millimeters, etc.) are correct according to the information in the bitmap. For example, 960 pixels wide at 96 dpi means 10" wide. On a 120 dpi display, this means displaying the bitmap large enough so that its width uses 1200 display pixels.

If you want or need the bitmap to display at exactly the same number of display pixels regardless of the display resolution, then you'll have to set a transform where you display the image to reverse the effect of the scaling that WPF would otherwise do. This requires knowing the display resolution, of course.

Here are some other related Stack Overflow questions which you might find useful: RenderTargetBitmap renders image of a wrong size
WPF for LCD screen Full HD
Screen Resolution Problem In WPF?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download