Search code examples
c#imageheightwidth

Wrong image width and height when read it with C#


I've got a strange problem. There is an image. Unfortunately it's too big to show it in question. But you can download it. If you can't do it from OneDrive this is another way.

This image seems to be ordinary, but it's not.

When we open properties we will see this:

Image properties in Windows

We need to keep in mind dimensions of this picture: Width is 3000px and Height is 4000px. It looks correct because image is portret.

Then lets try to read it with C#:

private static void TestImage()
{
    using (FileStream file1 = new FileStream("DSC_2446.JPG", FileMode.Open))
    {                
        Console.WriteLine("DSC_2446.JPG :");
        using (var img1 = System.Drawing.Image.FromStream(file1))
        {
            Console.WriteLine($" Width = {img1.Width}");
            Console.WriteLine($" Height = {img1.Height}");
        } 
    }                

    Console.Read();
}

And in results we see some magic!!!

Magic results

So I've got completely wrong values. Values are switched between properties. Does someone know why it can happens and how to detect/fix this behavior?


Solution

  • The problem is the EXIF version. You can use this site to get the real data https://exif.tools/meta/Exif-Version/0231 and you will see

    enter image description here

    Also according to this Post you can get your image's orientation by

    var orientation = (int)img1.GetPropertyItem(274).Value[0];
    //orientation = 6
    

    the value 6 means rotate 90 degrees.

    There is the reference of the value 6. https://exiftool.org/TagNames/EXIF.html

    enter image description here