//
// Copyright (c) James Jackson-South and contributors.
// Licensed under the Apache License, Version 2.0.
//
namespace ImageSharp
{
using System;
using Processing;
///
/// Extension methods for the type.
///
public static partial class ImageExtensions
{
///
/// Adjusts an image so that its orientation is suitable for viewing. Adjustments are based on EXIF metadata embedded in the image.
///
/// The pixel format.
/// The image to auto rotate.
/// The
public static Image AutoOrient(this Image source)
where TColor : struct, IPackedPixel, IEquatable
{
Orientation orientation = GetExifOrientation(source);
switch (orientation)
{
case Orientation.TopRight:
return source.Flip(FlipType.Horizontal);
case Orientation.BottomRight:
return source.Rotate(RotateType.Rotate180);
case Orientation.BottomLeft:
return source.Flip(FlipType.Vertical);
case Orientation.LeftTop:
return source.Rotate(RotateType.Rotate90)
.Flip(FlipType.Horizontal);
case Orientation.RightTop:
return source.Rotate(RotateType.Rotate90);
case Orientation.RightBottom:
return source.Flip(FlipType.Vertical)
.Rotate(RotateType.Rotate270);
case Orientation.LeftBottom:
return source.Rotate(RotateType.Rotate270);
case Orientation.Unknown:
case Orientation.TopLeft:
default:
return source;
}
}
///
/// Returns the current EXIF orientation
///
/// The pixel format.
/// The image to auto rotate.
/// The
private static Orientation GetExifOrientation(Image source)
where TColor : struct, IPackedPixel, IEquatable
{
if (source.ExifProfile == null)
{
return Orientation.Unknown;
}
ExifValue value = source.ExifProfile.GetValue(ExifTag.Orientation);
if (value == null)
{
return Orientation.Unknown;
}
Orientation orientation = (Orientation)value.Value;
source.ExifProfile.SetValue(ExifTag.Orientation, (ushort)Orientation.TopLeft);
return orientation;
}
}
}