Home > Software engineering >  Get the size of a displayed image inside a WPF ImageControl
Get the size of a displayed image inside a WPF ImageControl

Time:03-23

I have an image inside an image control of WPF.

How can I get the displayed size of the image inside the imageControl with the height and width converted to IN?

CodePudding user response:

Size displayedImageSize = new Size((int)imageControl.ActualWidth, (int)imageControl.ActualHeight);

CodePudding user response:

I tested Tam Bui solution, it does not work properly when the image size is smaller than the image control size.

My solution: first put the image in MemoryStream, then convert it to BitmapImage and finally get the height and width of BitmapImage.

Output (tested in Visual Studio 2017, .Net Framework 4.5.2):

I tested it on png and jpg images.

Output

Note: if this solution helps you, please mark as answer (don't forget to vote for me).

XAML:

    <Image x:Name="ImageControl" HorizontalAlignment="Left" Height="184" Margin="48,35,0,0" VerticalAlignment="Top" Width="256"/>
    <Button Content="Selection" HorizontalAlignment="Left" Height="41" Margin="376,259,0,0" VerticalAlignment="Top" Width="118" Click="Button_Click"/>

C#:

    int Height = 0;
    int Width = 0;
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        System.Windows.Forms.OpenFileDialog OP = new System.Windows.Forms.OpenFileDialog();
        if(OP.ShowDialog()==System.Windows.Forms.DialogResult.OK)
        {
            var IMG = System.Drawing.Image.FromFile(OP.FileName);
            BitmapImage BitMapImage = new BitmapImage();
            BitMapImage.BeginInit();
            System.IO.MemoryStream MemoryStream = new System.IO.MemoryStream();
            IMG.Save(MemoryStream, System.Drawing.Imaging.ImageFormat.Png);
            MemoryStream.Seek(0, System.IO.SeekOrigin.Begin);
            BitMapImage.StreamSource = MemoryStream;
            BitMapImage.EndInit();
            Height = (int)BitMapImage.Height;
            Width = (int)BitMapImage.Width;   
            ImageControl.Source = BitMapImage;
        }
        Size DisplayedImageSize = new Size(Width, Height);
        MessageBox.Show("Image control height="   ImageControl.Height.ToString()   ", Image height="   Height.ToString()   ", Image control width = "   ImageControl.Width.ToString()   ", Image width="   Width.ToString());
    }

Thanks

  • Related