|
|
|
@ -1,6 +1,7 @@ |
|
|
|
// Copyright (c) Six Labors and contributors.
|
|
|
|
// Licensed under the Apache License, Version 2.0.
|
|
|
|
|
|
|
|
using System; |
|
|
|
using System.IO; |
|
|
|
using System.Linq; |
|
|
|
using SixLabors.ImageSharp.Formats; |
|
|
|
@ -47,19 +48,26 @@ namespace SixLabors.ImageSharp |
|
|
|
/// <returns>The mime type or null if none found.</returns>
|
|
|
|
private static IImageFormat InternalDetectFormat(Stream stream, Configuration config) |
|
|
|
{ |
|
|
|
// This is probably a candidate for making into a public API in the future!
|
|
|
|
int maxHeaderSize = config.MaxHeaderSize; |
|
|
|
if (maxHeaderSize <= 0) |
|
|
|
// We take a minimum of the stream length vs the max header size and always check below
|
|
|
|
// to ensure that only formats that headers fit within the given buffer length are tested.
|
|
|
|
int headerSize = (int)Math.Min(config.MaxHeaderSize, stream.Length); |
|
|
|
if (headerSize <= 0) |
|
|
|
{ |
|
|
|
return null; |
|
|
|
} |
|
|
|
|
|
|
|
using (IManagedByteBuffer buffer = config.MemoryAllocator.AllocateManagedByteBuffer(maxHeaderSize, AllocationOptions.Clean)) |
|
|
|
using (IManagedByteBuffer buffer = config.MemoryAllocator.AllocateManagedByteBuffer(headerSize, AllocationOptions.Clean)) |
|
|
|
{ |
|
|
|
long startPosition = stream.Position; |
|
|
|
stream.Read(buffer.Array, 0, maxHeaderSize); |
|
|
|
stream.Read(buffer.Array, 0, headerSize); |
|
|
|
stream.Position = startPosition; |
|
|
|
return config.ImageFormatsManager.FormatDetectors.Select(x => x.DetectFormat(buffer.GetSpan())).LastOrDefault(x => x != null); |
|
|
|
|
|
|
|
// Does the given stream contain enough data to fit in the header for the format
|
|
|
|
// and does that data match the format specification?
|
|
|
|
// Individual formats should still check since they are public.
|
|
|
|
return config.ImageFormatsManager.FormatDetectors |
|
|
|
.Where(x => x.HeaderSize <= headerSize) |
|
|
|
.Select(x => x.DetectFormat(buffer.GetSpan())).LastOrDefault(x => x != null); |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
|