diff --git a/src/ImageSharp/Image.FromBytes.cs b/src/ImageSharp/Image.FromBytes.cs index 8365dbd50b..98a39193d8 100644 --- a/src/ImageSharp/Image.FromBytes.cs +++ b/src/ImageSharp/Image.FromBytes.cs @@ -175,6 +175,33 @@ namespace SixLabors.ImageSharp #if !NETSTANDARD1_1 + /// + /// By reading the header on the provided byte array this calculates the images format. + /// + /// The byte array containing encoded image data to read the header from. + /// The format or null if none found. + public static IImageFormat DetectFormat(ReadOnlySpan data) + { + return DetectFormat(Configuration.Default, data); + } + + /// + /// By reading the header on the provided byte array this calculates the images format. + /// + /// The configuration. + /// The byte array containing encoded image data to read the header from. + /// The mime type or null if none found. + public static unsafe IImageFormat DetectFormat(Configuration config, ReadOnlySpan data) + { + fixed (byte* ptr = &data.GetPinnableReference()) + { + using (var stream = new UnmanagedMemoryStream(ptr, data.Length)) + { + return DetectFormat(config, stream); + } + } + } + /// /// Load a new instance of from the given encoded byte span. /// diff --git a/tests/ImageSharp.Tests/Image/ImageTests.DetectFormat.cs b/tests/ImageSharp.Tests/Image/ImageTests.DetectFormat.cs index c067bf29f2..9d709d488b 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.DetectFormat.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.DetectFormat.cs @@ -33,18 +33,27 @@ namespace SixLabors.ImageSharp.Tests private static readonly IImageFormat ExpectedGlobalFormat = Configuration.Default.ImageFormatsManager.FindFormatByFileExtension("bmp"); - [Fact] - public void FromBytes_GlobalConfiguration() + [Theory] + [InlineData(false)] + [InlineData(true)] + public void FromBytes_GlobalConfiguration(bool useSpan) { - IImageFormat type = Image.DetectFormat(this.ActualImageBytes); - + IImageFormat type = useSpan + ? Image.DetectFormat(this.ActualImageSpan) + : Image.DetectFormat(this.ActualImageBytes); + Assert.Equal(ExpectedGlobalFormat, type); } - [Fact] - public void FromBytes_CustomConfiguration() + [Theory] + [InlineData(false)] + [InlineData(true)] + public void FromBytes_CustomConfiguration(bool useSpan) { - IImageFormat type = Image.DetectFormat(this.LocalConfiguration, this.ByteArray); + IImageFormat type = useSpan + ? Image.DetectFormat(this.LocalConfiguration, this.ByteArray.AsSpan()) + : Image.DetectFormat(this.LocalConfiguration, this.ByteArray); + Assert.Equal(this.LocalImageFormat, type); }