2022-04-29 13:16:24 +02:00
|
|
|
using System;
|
2021-08-12 10:19:06 +02:00
|
|
|
using System.IO;
|
|
|
|
|
using SixLabors.ImageSharp;
|
2022-04-29 13:16:24 +02:00
|
|
|
using SixLabors.ImageSharp.Metadata.Profiles.Exif;
|
2021-08-12 10:19:06 +02:00
|
|
|
using Umbraco.Cms.Core.Media;
|
|
|
|
|
using Size = System.Drawing.Size;
|
|
|
|
|
|
|
|
|
|
namespace Umbraco.Cms.Infrastructure.Media
|
|
|
|
|
{
|
|
|
|
|
internal class ImageSharpDimensionExtractor : IImageDimensionExtractor
|
|
|
|
|
{
|
2021-09-08 15:18:29 +02:00
|
|
|
private readonly Configuration _configuration;
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Initializes a new instance of the <see cref="ImageSharpDimensionExtractor" /> class.
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="configuration">The configuration.</param>
|
|
|
|
|
public ImageSharpDimensionExtractor(Configuration configuration)
|
|
|
|
|
=> _configuration = configuration;
|
|
|
|
|
|
2021-08-12 10:19:06 +02:00
|
|
|
/// <summary>
|
|
|
|
|
/// Gets the dimensions of an image.
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="stream">A stream containing the image bytes.</param>
|
|
|
|
|
/// <returns>
|
|
|
|
|
/// The dimension of the image.
|
|
|
|
|
/// </returns>
|
2022-02-18 14:32:51 +01:00
|
|
|
public Size? GetDimensions(Stream? stream)
|
2021-08-12 10:19:06 +02:00
|
|
|
{
|
|
|
|
|
Size? size = null;
|
|
|
|
|
|
2021-09-08 15:18:29 +02:00
|
|
|
IImageInfo imageInfo = Image.Identify(_configuration, stream);
|
2021-08-12 10:19:06 +02:00
|
|
|
if (imageInfo != null)
|
|
|
|
|
{
|
2022-04-29 13:16:24 +02:00
|
|
|
size = IsExifOrientationRotated(imageInfo)
|
|
|
|
|
? new Size(imageInfo.Height, imageInfo.Width)
|
|
|
|
|
: new Size(imageInfo.Width, imageInfo.Height);
|
2021-08-12 10:19:06 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return size;
|
|
|
|
|
}
|
2022-04-29 13:16:24 +02:00
|
|
|
|
|
|
|
|
private static bool IsExifOrientationRotated(IImageInfo imageInfo)
|
|
|
|
|
=> GetExifOrientation(imageInfo) switch
|
|
|
|
|
{
|
|
|
|
|
ExifOrientationMode.LeftTop
|
|
|
|
|
or ExifOrientationMode.RightTop
|
|
|
|
|
or ExifOrientationMode.RightBottom
|
|
|
|
|
or ExifOrientationMode.LeftBottom => true,
|
|
|
|
|
_ => false,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
private static ushort GetExifOrientation(IImageInfo imageInfo)
|
|
|
|
|
{
|
2022-04-29 15:02:36 +02:00
|
|
|
IExifValue<ushort>? orientation = imageInfo.Metadata.ExifProfile?.GetValue(ExifTag.Orientation);
|
2022-04-29 13:16:24 +02:00
|
|
|
if (orientation is not null)
|
|
|
|
|
{
|
|
|
|
|
if (orientation.DataType == ExifDataType.Short)
|
|
|
|
|
{
|
|
|
|
|
return orientation.Value;
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
return Convert.ToUInt16(orientation.Value);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return ExifOrientationMode.Unknown;
|
|
|
|
|
}
|
2021-08-12 10:19:06 +02:00
|
|
|
}
|
|
|
|
|
}
|