sábado, 27 de octubre de 2018

Reset Image Orientation using EXIF in C#

Let's say you took the photos using smart phones or regular cameras in different orientation and in different angles (rotate the camera to 90°, 270° degrees, etc). And now you copy the photos to system and observe that, the photo orientation is incorrect.

When you upload these photos to other sites to set profile picture or  album picture or timeline photo, etc., you will see that photos were uploaded with incorrect orientation.

So, sometimes we need to re-orient the photos as per the orientation recorded by cameras. The orientation information is stored in EXIF meta data of each photo. 

The following C# code will correct the orientation, if you capture the photos from any device, in any angles..

Microsoft RotateFlipType Enumeration https://docs.microsoft.com/en-us/windows/desktop/api/gdiplusimaging/ne-gdiplusimaging-rotatefliptype

original Link https://www.dotnet4techies.com/2014/09/reset-image-orientation-using-exif-in-c.html

 string sImage = @"E:\srinivas\DSC01.jpg";
    Image img = Image.FromFile(sImage);
 
    foreach (var prop in img.PropertyItems)
    {
        if (prop.Id == 0x0112) //value of EXIF
        {
            int orientationValue = img.GetPropertyItem(prop.Id).Value[0];
            RotateFlipType rotateFlipType = GetOrientationToFlipType(orientationValue);
            img.RotateFlip(rotateFlipType);
            img.Save(@"E:\srinivas\DSC01_modified.jpg");
            break;
        }
    }
 
private static RotateFlipType GetOrientationToFlipType(int orientationValue)
{
    RotateFlipType rotateFlipType = RotateFlipType.RotateNoneFlipNone;
 
    switch (orientationValue)
    {
        case 1:
            rotateFlipType = RotateFlipType.RotateNoneFlipNone;
            break;
        case 2:
            rotateFlipType = RotateFlipType.RotateNoneFlipX;
            break;
        case 3:
            rotateFlipType = RotateFlipType.Rotate180FlipNone;
            break;
        case 4:
            rotateFlipType = RotateFlipType.Rotate180FlipX;
            break;
        case 5:
            rotateFlipType = RotateFlipType.Rotate90FlipX;
            break;
        case 6:
            rotateFlipType = RotateFlipType.Rotate90FlipNone;
            break;
        case 7:
            rotateFlipType = RotateFlipType.Rotate270FlipX;
            break;
        case 8:
            rotateFlipType = RotateFlipType.Rotate270FlipNone;
            break;
        default:
            rotateFlipType = RotateFlipType.RotateNoneFlipNone;
            break;
    }
 
    return rotateFlipType;
}

0 comentarios:

Publicar un comentario