How to get the the dimensions of an image file?

C#ImageDimensions

C# Problem Overview


I have a file called FPN = "c:\ggs\ggs Access\images\members\1.jpg "

I'm trying to get the dimension of image 1.jpg, and I'd like to check whether image dimension is valid or not before loading.

C# Solutions


Solution 1 - C#

System.Drawing.Image img = System.Drawing.Image.FromFile(@"c:\ggs\ggs Access\images\members\1.jpg");
MessageBox.Show("Width: " + img.Width + ", Height: " + img.Height);

Solution 2 - C#

Wpf class System.Windows.Media.Imaging.BitmapDecoder doesn't read whole file, just metadata.

using(var imageStream = File.OpenRead("file"))
{
    var decoder = BitmapDecoder.Create(imageStream, BitmapCreateOptions.IgnoreColorProfile,
        BitmapCacheOption.Default);
    var height = decoder.Frames[0].PixelHeight;
    var width = decoder.Frames[0].PixelWidth;
}

Update 2019-07-07 Dealing with exif'ed images is a little bit more complicated. For some reasons iphones save a rotated image and to compensate they also set "rotate this image before displaying" exif flag as such.

Gif is also a pretty complicated format. It is possible that no frame has full gif size, you have to aggregate it from offsets and frames sizes.

So I used ImageProcessor instead, which deals with all the problems for me. Never checked if it reads the whole file though, because some browsers have no exif support and I had to save a rotated version anyway.

using (var imageFactory = new ImageFactory())
{
    imageFactory
        .Load(stream)
        .AutoRotate(); //takes care of ex-if
    var height = imageFactory.Image.Height,
    var width = imageFactory.Image.Width
}

Solution 3 - C#

Unfortunately, System.Drawing and ImageProcessor are supported only on the Windows platform because they are a thin wrapper over GDI (Graphics Device Interface) which is very old Win32 (Windows) unmanaged drawing APIs.

Instead, just install the SixLabors/ImageSharp library from NuGet. And here is how you can get size with it:

using (var image = SixLabors.ImageSharp.Image.Load("image-path."))
{
    var width = image.Width;
    var height = image.Height;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser682417View Question on Stackoverflow
Solution 1 - C#John TView Answer on Stackoverflow
Solution 2 - C#AtomoskView Answer on Stackoverflow
Solution 3 - C#PalindromerView Answer on Stackoverflow