Search code examples
wpfimagepixeldpi

Wpf: Making image display pixel perfect at original size


I have an image that is 24x24. If i do not enter width and height in xaml and set Stretch="None" my 24x24 will size up to 32x32. Shouldn't 'no stretch' mean that the image displays at 24x24?

If i forcibly set the image to 24x24 then i get extra pixels that are not there in the original image.

I would like the image to be displayed at 100% size/scale with "pixel perfect"/"point filtering" rendering.

enter image description here

I read on a related question that something about some images having 96 DPI and some 72 which can cause weird behavior. I tried checking the DPI of my image following a tutorial, but there is no DPI info in the place the tutorial said (at the red line): enter image description here

Either way, even if i fix so the image DPI is the same as my screen DPI (dont know how to check that either) wont't there be a problem on other people's screens? I don't want the image to be pixel perfect on only 96 DPI screens. I want it to be pixel perfect always, i always want 1 pixel of the image to correspond to 1 pixel in the application/on-screen.

Is this impossible to achieve in WPF? If it is, how can i at least make it so the awkward extra pixels are "uniform" (look at the image in the middle, it has extra pixels on the width but not height) and so that all images scale the same way (depending on where in the window the image is placed the extra pixels are in different places, i would like every instance of the same image to look the same).


Solution

  • In order to size an Image element to the PixelWidth and PixelHeight of its Source image, you may bind its Width and Height like shown below.

    Also set RenderOptions.BitmapScalingMode to NearestNeighbor to avoid pixel interpolation.

    <Image ...
        Width="{Binding Source.PixelWidth, RelativeSource={RelativeSource Self}}"
        Height="{Binding Source.PixelHeight, RelativeSource={RelativeSource Self}}"
        Stretch="Fill"
        RenderOptions.BitmapScalingMode="NearestNeighbor"/>