7

How can I determine the size of an ImageSource in pixels? The ImageSource object has a Height and a Width property, but they return the size in 1/96 inches..

eflorico
  • 3,589
  • 2
  • 30
  • 41

4 Answers4

10

Super old post, but for anyone else having problems with this, you don't have to do anything crazy or complicated.

(ImageSource.Source as BitmapSource).PixelWidth
(ImageSource.Source as BitmapSource).PixelHeight
Mutex
  • 109
  • 1
  • 4
7

There are 2 types of ImageSource: DrawingImage and BitmapSource.

Obviously, DrawingImage does not have DPI or pixel width, because it's essentially vector graphic.

On other side, BitmapSource has PixeWidth/PixelHeight and also DpiX/DpiY.

http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapsource.pixelheight.aspx

Oleg Mihailik
  • 2,514
  • 2
  • 19
  • 32
6

You have to multiply the value with Windows's DPI resolution in order to obtain the amount of physical pixels. One way to get the DPI resolution is to get hold of a Graphics object and read its DpiX and DpiY properties.

Tormod Fjeldskår
  • 5,952
  • 1
  • 29
  • 47
0

Borrowing from what I found here I came up with:

Inside the Image Tag in XAML do:

<Image.Resources>
    <c:StringJoinConverter x:Key="StringJoin" />
</Image.Resources>
<Image.Tag>
    <!-- Get Image's actual width & height and store it in the control's Tag -->
    <MultiBinding Converter="{StaticResource StringJoin}">
        <Binding RelativeSource="{RelativeSource Self}" Path="Source.PixelWidth" />
        <Binding RelativeSource="{RelativeSource Self}" Path="Source.PixelHeight" />
    </MultiBinding>
</Image.Tag>

You will have to setup your c namespace at the top of your XAML file for your Converter's folder/namespace like:

xmlns:c="clr-namespace:Project.Converters"

Then creating the Converter:

public class StringJoinConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return string.Join((parameter ?? ",").ToString(), values);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

You can then later extract the actual(pixel) Width & Height of the image with:

var tag = imageControl.Tag; // width,height
List<double> size = tag.ToString()
                       .Split(',')
                       .Select(d => Convert.ToDouble(d))
                       .ToList();
double imageWidth = size[0],
       imageHeight = size[1];
Community
  • 1
  • 1
Chuck Savage
  • 11,775
  • 6
  • 49
  • 69