diff --git a/src/ImageSharp/Formats/Bmp/BmpDecoder.cs b/src/ImageSharp/Formats/Bmp/BmpDecoder.cs
index 8b53194fdc..78a9de6c45 100644
--- a/src/ImageSharp/Formats/Bmp/BmpDecoder.cs
+++ b/src/ImageSharp/Formats/Bmp/BmpDecoder.cs
@@ -1,8 +1,6 @@
// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
-using System;
-using System.Collections.Generic;
using System.IO;
using SixLabors.ImageSharp.PixelFormats;
@@ -23,7 +21,7 @@ namespace SixLabors.ImageSharp.Formats.Bmp
/// Formats will be supported in a later releases. We advise always
/// to use only 24 Bit Windows bitmaps.
///
- public sealed class BmpDecoder : IImageDecoder, IBmpDecoderOptions
+ public sealed class BmpDecoder : IImageDecoder, IBmpDecoderOptions, IImageInfoDetector
{
///
public Image Decode(Configuration configuration, Stream stream)
@@ -34,5 +32,13 @@ public Image Decode(Configuration configuration, Stream stream)
return new BmpDecoderCore(configuration, this).Decode(stream);
}
+
+ ///
+ public IImageInfo Identify(Configuration configuration, Stream stream)
+ {
+ Guard.NotNull(stream, "stream");
+
+ return new BmpDecoderCore(configuration, this).Identify(stream);
+ }
}
}
diff --git a/src/ImageSharp/Formats/Bmp/BmpDecoderCore.cs b/src/ImageSharp/Formats/Bmp/BmpDecoderCore.cs
index 04176e0333..e552ac1042 100644
--- a/src/ImageSharp/Formats/Bmp/BmpDecoderCore.cs
+++ b/src/ImageSharp/Formats/Bmp/BmpDecoderCore.cs
@@ -5,6 +5,7 @@
using System.IO;
using System.Runtime.CompilerServices;
using SixLabors.ImageSharp.Memory;
+using SixLabors.ImageSharp.MetaData;
using SixLabors.ImageSharp.PixelFormats;
namespace SixLabors.ImageSharp.Formats.Bmp
@@ -94,62 +95,9 @@ public BmpDecoderCore(Configuration configuration, IBmpDecoderOptions options)
public Image Decode(Stream stream)
where TPixel : struct, IPixel
{
- this.currentStream = stream;
-
try
{
- this.ReadFileHeader();
- this.ReadInfoHeader();
-
- // see http://www.drdobbs.com/architecture-and-design/the-bmp-file-format-part-1/184409517
- // If the height is negative, then this is a Windows bitmap whose origin
- // is the upper-left corner and not the lower-left.The inverted flag
- // indicates a lower-left origin.Our code will be outputting an
- // upper-left origin pixel array.
- bool inverted = false;
- if (this.infoHeader.Height < 0)
- {
- inverted = true;
- this.infoHeader.Height = -this.infoHeader.Height;
- }
-
- int colorMapSize = -1;
-
- if (this.infoHeader.ClrUsed == 0)
- {
- if (this.infoHeader.BitsPerPixel == 1 ||
- this.infoHeader.BitsPerPixel == 4 ||
- this.infoHeader.BitsPerPixel == 8)
- {
- colorMapSize = (int)Math.Pow(2, this.infoHeader.BitsPerPixel) * 4;
- }
- }
- else
- {
- colorMapSize = this.infoHeader.ClrUsed * 4;
- }
-
- byte[] palette = null;
-
- if (colorMapSize > 0)
- {
- // 256 * 4
- if (colorMapSize > 1024)
- {
- throw new ImageFormatException($"Invalid bmp colormap size '{colorMapSize}'");
- }
-
- palette = new byte[colorMapSize];
-
- this.currentStream.Read(palette, 0, colorMapSize);
- }
-
- if (this.infoHeader.Width > int.MaxValue || this.infoHeader.Height > int.MaxValue)
- {
- throw new ArgumentOutOfRangeException(
- $"The input bitmap '{this.infoHeader.Width}x{this.infoHeader.Height}' is "
- + $"bigger then the max allowed size '{int.MaxValue}x{int.MaxValue}'");
- }
+ this.ReadImageHeaders(stream, out bool inverted, out byte[] palette);
var image = new Image(this.configuration, this.infoHeader.Width, this.infoHeader.Height);
using (PixelAccessor pixels = image.Lock())
@@ -192,6 +140,16 @@ public Image Decode(Stream stream)
}
}
+ ///
+ /// Reads the raw image information from the specified stream.
+ ///
+ /// The containing image data.
+ public IImageInfo Identify(Stream stream)
+ {
+ this.ReadImageHeaders(stream, out _, out _);
+ return new ImageInfo(new PixelTypeInfo(this.infoHeader.BitsPerPixel), this.infoHeader.Width, this.infoHeader.Height, new ImageMetaData());
+ }
+
///
/// Returns the y- value based on the given height.
///
@@ -624,5 +582,73 @@ private void ReadFileHeader()
Offset = BitConverter.ToInt32(data, 10)
};
}
+
+ ///
+ /// Reads the and from the stream and sets the corresponding fields.
+ ///
+ private void ReadImageHeaders(Stream stream, out bool inverted, out byte[] palette)
+ {
+ this.currentStream = stream;
+
+ try
+ {
+ this.ReadFileHeader();
+ this.ReadInfoHeader();
+
+ // see http://www.drdobbs.com/architecture-and-design/the-bmp-file-format-part-1/184409517
+ // If the height is negative, then this is a Windows bitmap whose origin
+ // is the upper-left corner and not the lower-left.The inverted flag
+ // indicates a lower-left origin.Our code will be outputting an
+ // upper-left origin pixel array.
+ inverted = false;
+ if (this.infoHeader.Height < 0)
+ {
+ inverted = true;
+ this.infoHeader.Height = -this.infoHeader.Height;
+ }
+
+ int colorMapSize = -1;
+
+ if (this.infoHeader.ClrUsed == 0)
+ {
+ if (this.infoHeader.BitsPerPixel == 1 ||
+ this.infoHeader.BitsPerPixel == 4 ||
+ this.infoHeader.BitsPerPixel == 8)
+ {
+ colorMapSize = (int)Math.Pow(2, this.infoHeader.BitsPerPixel) * 4;
+ }
+ }
+ else
+ {
+ colorMapSize = this.infoHeader.ClrUsed * 4;
+ }
+
+ palette = null;
+
+ if (colorMapSize > 0)
+ {
+ // 256 * 4
+ if (colorMapSize > 1024)
+ {
+ throw new ImageFormatException($"Invalid bmp colormap size '{colorMapSize}'");
+ }
+
+ palette = new byte[colorMapSize];
+
+ this.currentStream.Read(palette, 0, colorMapSize);
+ }
+
+ if (this.infoHeader.Width > int.MaxValue || this.infoHeader.Height > int.MaxValue)
+ {
+ throw new ArgumentOutOfRangeException(
+ $"The input bitmap '{this.infoHeader.Width}x{this.infoHeader.Height}' is "
+ + $"bigger then the max allowed size '{int.MaxValue}x{int.MaxValue}'");
+ }
+ }
+ catch (IndexOutOfRangeException e)
+ {
+ throw new ImageFormatException("Bitmap does not have a valid format.", e);
+ }
+ }
}
}
\ No newline at end of file
diff --git a/src/ImageSharp/Formats/Gif/GifDecoder.cs b/src/ImageSharp/Formats/Gif/GifDecoder.cs
index 11b5b57fa2..c81c51e8b4 100644
--- a/src/ImageSharp/Formats/Gif/GifDecoder.cs
+++ b/src/ImageSharp/Formats/Gif/GifDecoder.cs
@@ -1,8 +1,6 @@
// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
-using System;
-using System.Collections.Generic;
using System.IO;
using System.Text;
using SixLabors.ImageSharp.PixelFormats;
@@ -12,7 +10,7 @@ namespace SixLabors.ImageSharp.Formats.Gif
///
/// Decoder for generating an image out of a gif encoded stream.
///
- public sealed class GifDecoder : IImageDecoder, IGifDecoderOptions
+ public sealed class GifDecoder : IImageDecoder, IGifDecoderOptions, IImageInfoDetector
{
///
/// Gets or sets a value indicating whether the metadata should be ignored when the image is being decoded.
@@ -33,8 +31,17 @@ public sealed class GifDecoder : IImageDecoder, IGifDecoderOptions
public Image Decode(Configuration configuration, Stream stream)
where TPixel : struct, IPixel
{
- var decoder = new GifDecoderCore(configuration, this);
- return decoder.Decode(stream);
+ var decoder = new GifDecoderCore(configuration, this);
+ return decoder.Decode(stream);
+ }
+
+ ///
+ public IImageInfo Identify(Configuration configuration, Stream stream)
+ {
+ Guard.NotNull(stream, "stream");
+
+ var decoder = new GifDecoderCore(configuration, this);
+ return decoder.Identify(stream);
}
}
}
diff --git a/src/ImageSharp/Formats/Gif/GifDecoderCore.cs b/src/ImageSharp/Formats/Gif/GifDecoderCore.cs
index ae20be7d5d..3c22518057 100644
--- a/src/ImageSharp/Formats/Gif/GifDecoderCore.cs
+++ b/src/ImageSharp/Formats/Gif/GifDecoderCore.cs
@@ -17,9 +17,7 @@ namespace SixLabors.ImageSharp.Formats.Gif
///
/// Performs the gif decoding operation.
///
- /// The pixel format.
- internal sealed class GifDecoderCore
- where TPixel : struct, IPixel
+ internal sealed class GifDecoderCore
{
///
/// The temp buffer used to reduce allocations.
@@ -46,11 +44,6 @@ internal sealed class GifDecoderCore
///
private int globalColorTableLength;
- ///
- /// The previous frame.
- ///
- private ImageFrame previousFrame;
-
///
/// The area to restore.
///
@@ -72,12 +65,7 @@ internal sealed class GifDecoderCore
private ImageMetaData metaData;
///
- /// The image to decode the information to.
- ///
- private Image image;
-
- ///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The configuration.
/// The decoder options.
@@ -107,28 +95,17 @@ public GifDecoderCore(Configuration configuration, IGifDecoderOptions options)
///
/// Decodes the stream to the image.
///
+ /// The pixel format.
/// The stream containing image data.
/// The decoded image
- public Image Decode(Stream stream)
+ public Image Decode(Stream stream)
+ where TPixel : struct, IPixel
{
+ Image image = null;
+ ImageFrame previousFrame = null;
try
{
- this.metaData = new ImageMetaData();
-
- this.currentStream = stream;
-
- // Skip the identifier
- this.currentStream.Skip(6);
- this.ReadLogicalScreenDescriptor();
-
- if (this.logicalScreenDescriptor.GlobalColorTableFlag)
- {
- this.globalColorTableLength = this.logicalScreenDescriptor.GlobalColorTableSize * 3;
- this.globalColorTable = Buffer.CreateClean(this.globalColorTableLength);
-
- // Read the global color table from the stream
- stream.Read(this.globalColorTable.Array, 0, this.globalColorTableLength);
- }
+ this.ReadLogicalScreenDescriptorAndGlobalColorTable(stream);
// Loop though the respective gif parts and read the data.
int nextFlag = stream.ReadByte();
@@ -136,12 +113,12 @@ public Image Decode(Stream stream)
{
if (nextFlag == GifConstants.ImageLabel)
{
- if (this.previousFrame != null && this.DecodingMode == FrameDecodingMode.First)
+ if (previousFrame != null && this.DecodingMode == FrameDecodingMode.First)
{
break;
}
- this.ReadFrame();
+ this.ReadFrame(ref image, ref previousFrame);
}
else if (nextFlag == GifConstants.ExtensionIntroducer)
{
@@ -184,7 +161,72 @@ public Image Decode(Stream stream)
this.globalColorTable?.Dispose();
}
- return this.image;
+ return image;
+ }
+
+ ///
+ /// Reads the raw image information from the specified stream.
+ ///
+ /// The containing image data.
+ public IImageInfo Identify(Stream stream)
+ {
+ try
+ {
+ this.ReadLogicalScreenDescriptorAndGlobalColorTable(stream);
+
+ // Loop though the respective gif parts and read the data.
+ int nextFlag = stream.ReadByte();
+ while (nextFlag != GifConstants.Terminator)
+ {
+ if (nextFlag == GifConstants.ImageLabel)
+ {
+ // Skip image block
+ this.Skip(0);
+ }
+ else if (nextFlag == GifConstants.ExtensionIntroducer)
+ {
+ int label = stream.ReadByte();
+ switch (label)
+ {
+ case GifConstants.GraphicControlLabel:
+
+ // Skip graphic control extension block
+ this.Skip(0);
+ break;
+ case GifConstants.CommentLabel:
+ this.ReadComments();
+ break;
+ case GifConstants.ApplicationExtensionLabel:
+
+ // The application extension length should be 11 but we've got test images that incorrectly
+ // set this to 252.
+ int appLength = stream.ReadByte();
+ this.Skip(appLength); // No need to read.
+ break;
+ case GifConstants.PlainTextLabel:
+ int plainLength = stream.ReadByte();
+ this.Skip(plainLength); // Not supported by any known decoder.
+ break;
+ }
+ }
+ else if (nextFlag == GifConstants.EndIntroducer)
+ {
+ break;
+ }
+
+ nextFlag = stream.ReadByte();
+ if (nextFlag == -1)
+ {
+ break;
+ }
+ }
+ }
+ finally
+ {
+ this.globalColorTable?.Dispose();
+ }
+
+ return new ImageInfo(new PixelTypeInfo(this.logicalScreenDescriptor.BitsPerPixel), this.logicalScreenDescriptor.Width, this.logicalScreenDescriptor.Height, this.metaData);
}
///
@@ -242,6 +284,7 @@ private void ReadLogicalScreenDescriptor()
{
Width = BitConverter.ToInt16(this.buffer, 0),
Height = BitConverter.ToInt16(this.buffer, 2),
+ BitsPerPixel = (this.buffer[4] & 0x07) + 1, // The lowest 3 bits represent the bit depth minus 1
BackgroundColorIndex = this.buffer[5],
PixelAspectRatio = this.buffer[6],
GlobalColorTableFlag = ((packed & 0x80) >> 7) == 1,
@@ -308,7 +351,11 @@ private void ReadComments()
///
/// Reads an individual gif frame.
///
- private void ReadFrame()
+ /// The pixel format.
+ /// The image to decode the information to.
+ /// The previous frame.
+ private void ReadFrame(ref Image image, ref ImageFrame previousFrame)
+ where TPixel : struct, IPixel
{
GifImageDescriptor imageDescriptor = this.ReadImageDescriptor();
@@ -327,7 +374,7 @@ private void ReadFrame()
indices = Buffer.CreateClean(imageDescriptor.Width * imageDescriptor.Height);
this.ReadFrameIndices(imageDescriptor, indices);
- this.ReadFrameColors(indices, localColorTable ?? this.globalColorTable, imageDescriptor);
+ this.ReadFrameColors(ref image, ref previousFrame, indices, localColorTable ?? this.globalColorTable, imageDescriptor);
// Skip any remaining blocks
this.Skip(0);
@@ -357,10 +404,14 @@ private void ReadFrameIndices(GifImageDescriptor imageDescriptor, Span ind
///
/// Reads the frames colors, mapping indices to colors.
///
+ /// The pixel format.
+ /// The image to decode the information to.
+ /// The previous frame.
/// The indexed pixels.
/// The color table containing the available colors.
/// The
- private void ReadFrameColors(Span indices, Span colorTable, GifImageDescriptor descriptor)
+ private void ReadFrameColors(ref Image image, ref ImageFrame previousFrame, Span indices, Span colorTable, GifImageDescriptor descriptor)
+ where TPixel : struct, IPixel
{
int imageWidth = this.logicalScreenDescriptor.Width;
int imageHeight = this.logicalScreenDescriptor.Height;
@@ -371,30 +422,30 @@ private void ReadFrameColors(Span indices, Span colorTable, GifImage
ImageFrame imageFrame;
- if (this.previousFrame == null)
+ if (previousFrame == null)
{
// This initializes the image to become fully transparent because the alpha channel is zero.
- this.image = new Image(this.configuration, imageWidth, imageHeight, this.metaData);
+ image = new Image(this.configuration, imageWidth, imageHeight, this.metaData);
- this.SetFrameMetaData(this.image.Frames.RootFrame.MetaData);
+ this.SetFrameMetaData(image.Frames.RootFrame.MetaData);
- imageFrame = this.image.Frames.RootFrame;
+ imageFrame = image.Frames.RootFrame;
}
else
{
if (this.graphicsControlExtension != null &&
this.graphicsControlExtension.DisposalMethod == DisposalMethod.RestoreToPrevious)
{
- prevFrame = this.previousFrame;
+ prevFrame = previousFrame;
}
- currentFrame = this.image.Frames.AddFrame(this.previousFrame); // This clones the frame and adds it the collection
+ currentFrame = image.Frames.AddFrame(previousFrame); // This clones the frame and adds it the collection
this.SetFrameMetaData(currentFrame.MetaData);
imageFrame = currentFrame;
- this.RestoreToBackground(imageFrame);
+ this.RestoreToBackground(imageFrame, image.Width, image.Height);
}
int i = 0;
@@ -466,11 +517,11 @@ private void ReadFrameColors(Span indices, Span colorTable, GifImage
if (prevFrame != null)
{
- this.previousFrame = prevFrame;
+ previousFrame = prevFrame;
return;
}
- this.previousFrame = currentFrame ?? this.image.Frames.RootFrame;
+ previousFrame = currentFrame ?? image.Frames.RootFrame;
if (this.graphicsControlExtension != null &&
this.graphicsControlExtension.DisposalMethod == DisposalMethod.RestoreToBackground)
@@ -482,8 +533,12 @@ private void ReadFrameColors(Span indices, Span colorTable, GifImage
///
/// Restores the current frame area to the background.
///
+ /// The pixel format.
/// The frame.
- private void RestoreToBackground(ImageFrame frame)
+ /// Width of the image.
+ /// Height of the image.
+ private void RestoreToBackground(ImageFrame frame, int imageWidth, int imageHeight)
+ where TPixel : struct, IPixel
{
if (this.restoreArea == null)
{
@@ -491,8 +546,8 @@ private void RestoreToBackground(ImageFrame frame)
}
// Optimization for when the size of the frame is the same as the image size.
- if (this.restoreArea.Value.Width == this.image.Width &&
- this.restoreArea.Value.Height == this.image.Height)
+ if (this.restoreArea.Value.Width == imageWidth &&
+ this.restoreArea.Value.Height == imageHeight)
{
using (PixelAccessor pixelAccessor = frame.Lock())
{
@@ -533,5 +588,29 @@ private void SetFrameMetaData(ImageFrameMetaData meta)
meta.DisposalMethod = this.graphicsControlExtension.DisposalMethod;
}
}
+
+ ///
+ /// Reads the logical screen descriptor and global color table blocks
+ ///
+ /// The stream containing image data.
+ private void ReadLogicalScreenDescriptorAndGlobalColorTable(Stream stream)
+ {
+ this.metaData = new ImageMetaData();
+
+ this.currentStream = stream;
+
+ // Skip the identifier
+ this.currentStream.Skip(6);
+ this.ReadLogicalScreenDescriptor();
+
+ if (this.logicalScreenDescriptor.GlobalColorTableFlag)
+ {
+ this.globalColorTableLength = this.logicalScreenDescriptor.GlobalColorTableSize * 3;
+ this.globalColorTable = Buffer.CreateClean(this.globalColorTableLength);
+
+ // Read the global color table from the stream
+ stream.Read(this.globalColorTable.Array, 0, this.globalColorTableLength);
+ }
+ }
}
}
\ No newline at end of file
diff --git a/src/ImageSharp/Formats/Gif/Sections/GifLogicalScreenDescriptor.cs b/src/ImageSharp/Formats/Gif/Sections/GifLogicalScreenDescriptor.cs
index b1109c3e25..05f232a4be 100644
--- a/src/ImageSharp/Formats/Gif/Sections/GifLogicalScreenDescriptor.cs
+++ b/src/ImageSharp/Formats/Gif/Sections/GifLogicalScreenDescriptor.cs
@@ -22,6 +22,11 @@ internal sealed class GifLogicalScreenDescriptor
///
public short Height { get; set; }
+ ///
+ /// Gets or sets the color depth, in number of bits per pixel.
+ ///
+ public int BitsPerPixel { get; set; }
+
///
/// Gets or sets the index at the Global Color Table for the Background Color.
/// The Background Color is the color used for those
diff --git a/src/ImageSharp/Formats/IImageDecoder.cs b/src/ImageSharp/Formats/IImageDecoder.cs
index e392cf7c61..ffc40314d8 100644
--- a/src/ImageSharp/Formats/IImageDecoder.cs
+++ b/src/ImageSharp/Formats/IImageDecoder.cs
@@ -1,8 +1,6 @@
// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
-using System;
-using System.Collections.Generic;
using System.IO;
using SixLabors.ImageSharp.PixelFormats;
diff --git a/src/ImageSharp/Formats/IImageInfoDetector.cs b/src/ImageSharp/Formats/IImageInfoDetector.cs
new file mode 100644
index 0000000000..37bc0866fa
--- /dev/null
+++ b/src/ImageSharp/Formats/IImageInfoDetector.cs
@@ -0,0 +1,21 @@
+// Copyright (c) Six Labors and contributors.
+// Licensed under the Apache License, Version 2.0.
+
+using System.IO;
+
+namespace SixLabors.ImageSharp.Formats
+{
+ ///
+ /// Used for detecting the raw image information without decoding it.
+ ///
+ public interface IImageInfoDetector
+ {
+ ///
+ /// Reads the raw image information from the specified stream.
+ ///
+ /// The configuration for the image.
+ /// The containing image data.
+ /// The object
+ IImageInfo Identify(Configuration configuration, Stream stream);
+ }
+}
\ No newline at end of file
diff --git a/src/ImageSharp/Formats/Jpeg/GolangPort/OrigJpegDecoder.cs b/src/ImageSharp/Formats/Jpeg/GolangPort/OrigJpegDecoder.cs
index 13be70e30b..ecebe9480d 100644
--- a/src/ImageSharp/Formats/Jpeg/GolangPort/OrigJpegDecoder.cs
+++ b/src/ImageSharp/Formats/Jpeg/GolangPort/OrigJpegDecoder.cs
@@ -9,7 +9,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.GolangPort
///
/// Image decoder for generating an image out of a jpg stream.
///
- internal sealed class OrigJpegDecoder : IImageDecoder, IJpegDecoderOptions
+ internal sealed class OrigJpegDecoder : IImageDecoder, IJpegDecoderOptions, IImageInfoDetector
{
///
/// Gets or sets a value indicating whether the metadata should be ignored when the image is being decoded.
@@ -27,5 +27,16 @@ public Image Decode(Configuration configuration, Stream stream)
return decoder.Decode(stream);
}
}
+
+ ///
+ public IImageInfo Identify(Configuration configuration, Stream stream)
+ {
+ Guard.NotNull(stream, "stream");
+
+ using (var decoder = new OrigJpegDecoderCore(configuration, this))
+ {
+ return decoder.Identify(stream);
+ }
+ }
}
}
\ No newline at end of file
diff --git a/src/ImageSharp/Formats/Jpeg/GolangPort/OrigJpegDecoderCore.cs b/src/ImageSharp/Formats/Jpeg/GolangPort/OrigJpegDecoderCore.cs
index 61b18af551..d788b65c4b 100644
--- a/src/ImageSharp/Formats/Jpeg/GolangPort/OrigJpegDecoderCore.cs
+++ b/src/ImageSharp/Formats/Jpeg/GolangPort/OrigJpegDecoderCore.cs
@@ -31,6 +31,11 @@ internal sealed unsafe class OrigJpegDecoderCore : IRawJpegData
///
public const int MaxTq = 3;
+ ///
+ /// The only supported precision
+ ///
+ public const int SupportedPrecision = 8;
+
// Complex value type field + mutable + available to other classes = the field MUST NOT be private :P
#pragma warning disable SA1401 // FieldsMustBePrivate
@@ -122,6 +127,11 @@ public OrigJpegDecoderCore(Configuration configuration, IJpegDecoderOptions opti
IEnumerable IRawJpegData.Components => this.Components;
+ ///
+ /// Gets the color depth, in number of bits per pixel.
+ ///
+ public int BitsPerPixel => this.ComponentCount * SupportedPrecision;
+
///
/// Gets the image height
///
@@ -173,7 +183,7 @@ public OrigJpegDecoderCore(Configuration configuration, IJpegDecoderOptions opti
public ImageMetaData MetaData { get; private set; }
///
- /// Decodes the image from the specified and sets
+ /// Decodes the image from the specified and sets
/// the data to image.
///
/// The pixel format.
@@ -187,6 +197,16 @@ public Image Decode(Stream stream)
return this.PostProcessIntoImage();
}
+ ///
+ /// Reads the raw image information from the specified stream.
+ ///
+ /// The containing image data.
+ public IImageInfo Identify(Stream stream)
+ {
+ this.ParseStream(stream, true);
+ return new ImageInfo(new PixelTypeInfo(this.BitsPerPixel), this.ImageWidth, this.ImageHeight, this.MetaData);
+ }
+
///
public void Dispose()
{
@@ -627,7 +647,7 @@ private void ProcessStartOfFrameMarker(int remaining)
this.InputProcessor.ReadFull(this.Temp, 0, remaining);
// We only support 8-bit precision.
- if (this.Temp[0] != 8)
+ if (this.Temp[0] != SupportedPrecision)
{
throw new ImageFormatException("Only 8-Bit precision supported.");
}
diff --git a/src/ImageSharp/Formats/Jpeg/JpegDecoder.cs b/src/ImageSharp/Formats/Jpeg/JpegDecoder.cs
index 68f525305b..91835b5d71 100644
--- a/src/ImageSharp/Formats/Jpeg/JpegDecoder.cs
+++ b/src/ImageSharp/Formats/Jpeg/JpegDecoder.cs
@@ -4,7 +4,6 @@
using System.IO;
using SixLabors.ImageSharp.Formats.Jpeg.GolangPort;
-using SixLabors.ImageSharp.Formats.Jpeg.PdfJsPort;
using SixLabors.ImageSharp.PixelFormats;
namespace SixLabors.ImageSharp.Formats.Jpeg
@@ -12,7 +11,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg
///
/// Image decoder for generating an image out of a jpg stream.
///
- public sealed class JpegDecoder : IImageDecoder, IJpegDecoderOptions
+ public sealed class JpegDecoder : IImageDecoder, IJpegDecoderOptions, IImageInfoDetector
{
///
/// Gets or sets a value indicating whether the metadata should be ignored when the image is being decoded.
@@ -30,5 +29,16 @@ public Image Decode(Configuration configuration, Stream stream)
return decoder.Decode(stream);
}
}
+
+ ///
+ public IImageInfo Identify(Configuration configuration, Stream stream)
+ {
+ Guard.NotNull(stream, "stream");
+
+ using (var decoder = new OrigJpegDecoderCore(configuration, this))
+ {
+ return decoder.Identify(stream);
+ }
+ }
}
}
\ No newline at end of file
diff --git a/src/ImageSharp/Formats/PixelTypeInfo.cs b/src/ImageSharp/Formats/PixelTypeInfo.cs
new file mode 100644
index 0000000000..cdb6db8d9f
--- /dev/null
+++ b/src/ImageSharp/Formats/PixelTypeInfo.cs
@@ -0,0 +1,22 @@
+namespace SixLabors.ImageSharp.Formats
+{
+ ///
+ /// Stores the raw image pixel type information.
+ ///
+ public class PixelTypeInfo
+ {
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Color depth, in number of bits per pixel.
+ internal PixelTypeInfo(int bitsPerPixel)
+ {
+ this.BitsPerPixel = bitsPerPixel;
+ }
+
+ ///
+ /// Gets color depth, in number of bits per pixel.
+ ///
+ public int BitsPerPixel { get; }
+ }
+}
diff --git a/src/ImageSharp/Formats/Png/PngDecoder.cs b/src/ImageSharp/Formats/Png/PngDecoder.cs
index 739fd6051e..9bde4f8cc3 100644
--- a/src/ImageSharp/Formats/Png/PngDecoder.cs
+++ b/src/ImageSharp/Formats/Png/PngDecoder.cs
@@ -1,8 +1,6 @@
// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
-using System;
-using System.Collections.Generic;
using System.IO;
using System.Text;
using SixLabors.ImageSharp.PixelFormats;
@@ -29,7 +27,7 @@ namespace SixLabors.ImageSharp.Formats.Png
///
///
///
- public sealed class PngDecoder : IImageDecoder, IPngDecoderOptions
+ public sealed class PngDecoder : IImageDecoder, IPngDecoderOptions, IImageInfoDetector
{
///
/// Gets or sets a value indicating whether the metadata should be ignored when the image is being decoded.
@@ -54,5 +52,12 @@ public Image Decode(Configuration configuration, Stream stream)
var decoder = new PngDecoderCore(configuration, this);
return decoder.Decode(stream);
}
+
+ ///
+ public IImageInfo Identify(Configuration configuration, Stream stream)
+ {
+ var decoder = new PngDecoderCore(configuration, this);
+ return decoder.Identify(stream);
+ }
}
}
diff --git a/src/ImageSharp/Formats/Png/PngDecoderCore.cs b/src/ImageSharp/Formats/Png/PngDecoderCore.cs
index 7149b74d89..5c9b753e58 100644
--- a/src/ImageSharp/Formats/Png/PngDecoderCore.cs
+++ b/src/ImageSharp/Formats/Png/PngDecoderCore.cs
@@ -237,7 +237,7 @@ public Image Decode(Stream stream)
deframeStream.AllocateNewBytes(currentChunk.Length);
this.ReadScanlines(deframeStream.CompressedStream, image.Frames.RootFrame);
- stream.Read(this.crcBuffer, 0, 4);
+ this.currentStream.Read(this.crcBuffer, 0, 4);
break;
case PngChunkTypes.Palette:
byte[] pal = new byte[currentChunk.Length];
@@ -278,6 +278,66 @@ public Image Decode(Stream stream)
}
}
+ ///
+ /// Reads the raw image information from the specified stream.
+ ///
+ /// The containing image data.
+ public IImageInfo Identify(Stream stream)
+ {
+ var metadata = new ImageMetaData();
+ this.currentStream = stream;
+ this.currentStream.Skip(8);
+ try
+ {
+ PngChunk currentChunk;
+ while (!this.isEndChunkReached && (currentChunk = this.ReadChunk()) != null)
+ {
+ try
+ {
+ switch (currentChunk.Type)
+ {
+ case PngChunkTypes.Header:
+ this.ReadHeaderChunk(currentChunk.Data);
+ this.ValidateHeader();
+ break;
+ case PngChunkTypes.Physical:
+ this.ReadPhysicalChunk(metadata, currentChunk.Data);
+ break;
+ case PngChunkTypes.Data:
+ this.SkipChunkDataAndCrc(currentChunk);
+ break;
+ case PngChunkTypes.Text:
+ this.ReadTextChunk(metadata, currentChunk.Data, currentChunk.Length);
+ break;
+ case PngChunkTypes.End:
+ this.isEndChunkReached = true;
+ break;
+ }
+ }
+ finally
+ {
+ // Data is rented in ReadChunkData()
+ if (currentChunk.Data != null)
+ {
+ ArrayPool.Shared.Return(currentChunk.Data);
+ }
+ }
+ }
+ }
+ finally
+ {
+ this.scanline?.Dispose();
+ this.previousScanline?.Dispose();
+ }
+
+ if (this.header == null)
+ {
+ throw new ImageFormatException("PNG Image hasn't header chunk");
+ }
+
+ return new ImageInfo(new PixelTypeInfo(this.CalculateBitsPerPixel()), this.header.Width, this.header.Height, metadata);
+ }
+
///
/// Converts a byte array to a new array where each value in the original array is represented by the specified number of bits.
///
@@ -379,6 +439,28 @@ private void InitializeImage(ImageMetaData metadata, out Image i
this.scanline = Buffer.CreateClean(this.bytesPerScanline);
}
+ ///
+ /// Calculates the correct number of bits per pixel for the given color type.
+ ///
+ /// The
+ private int CalculateBitsPerPixel()
+ {
+ switch (this.pngColorType)
+ {
+ case PngColorType.Grayscale:
+ case PngColorType.Palette:
+ return this.header.BitDepth;
+ case PngColorType.GrayscaleWithAlpha:
+ return this.header.BitDepth * 2;
+ case PngColorType.Rgb:
+ return this.header.BitDepth * 3;
+ case PngColorType.RgbWithAlpha:
+ return this.header.BitDepth * 4;
+ default:
+ throw new NotSupportedException("Unsupported PNG color type");
+ }
+ }
+
///
/// Calculates the correct number of bytes per pixel for the given color type.
///
@@ -1181,6 +1263,15 @@ private void ReadChunkCrc(PngChunk chunk)
}
}
+ ///
+ /// Skips the chunk data and the cycle redundancy chunk read from the data.
+ ///
+ private void SkipChunkDataAndCrc(PngChunk chunk)
+ {
+ this.currentStream.Skip(chunk.Length);
+ this.currentStream.Skip(4);
+ }
+
///
/// Reads the chunk data from the stream.
///
diff --git a/src/ImageSharp/Image/IImage.cs b/src/ImageSharp/Image/IImage.cs
new file mode 100644
index 0000000000..afd00105e6
--- /dev/null
+++ b/src/ImageSharp/Image/IImage.cs
@@ -0,0 +1,9 @@
+namespace SixLabors.ImageSharp
+{
+ ///
+ /// Represents the base image abstraction.
+ ///
+ public interface IImage : IImageInfo
+ {
+ }
+}
\ No newline at end of file
diff --git a/src/ImageSharp/Image/IImageInfo.cs b/src/ImageSharp/Image/IImageInfo.cs
new file mode 100644
index 0000000000..b8dd59cc72
--- /dev/null
+++ b/src/ImageSharp/Image/IImageInfo.cs
@@ -0,0 +1,31 @@
+using SixLabors.ImageSharp.Formats;
+using SixLabors.ImageSharp.MetaData;
+
+namespace SixLabors.ImageSharp
+{
+ ///
+ /// Represents raw image information.
+ ///
+ public interface IImageInfo
+ {
+ ///
+ /// Gets the raw image pixel type information.
+ ///
+ PixelTypeInfo PixelType { get; }
+
+ ///
+ /// Gets the width.
+ ///
+ int Width { get; }
+
+ ///
+ /// Gets the height.
+ ///
+ int Height { get; }
+
+ ///
+ /// Gets the meta data of the image.
+ ///
+ ImageMetaData MetaData { get; }
+ }
+}
\ No newline at end of file
diff --git a/src/ImageSharp/Image/Image.Decode.cs b/src/ImageSharp/Image/Image.Decode.cs
index b4ab712d05..6af61f9f4a 100644
--- a/src/ImageSharp/Image/Image.Decode.cs
+++ b/src/ImageSharp/Image/Image.Decode.cs
@@ -79,5 +79,19 @@ private static (Image img, IImageFormat format) Decode(Stream st
Image img = decoder.Decode(config, stream);
return (img, format);
}
+
+ ///
+ /// Reads the image base information.
+ ///
+ /// The stream.
+ /// the configuration.
+ ///
+ /// The or null if suitable info detector not found.
+ ///
+ private static IImageInfo InternalIdentity(Stream stream, Configuration config)
+ {
+ var detector = DiscoverDecoder(stream, config, out IImageFormat _) as IImageInfoDetector;
+ return detector?.Identify(config, stream);
+ }
}
}
\ No newline at end of file
diff --git a/src/ImageSharp/Image/Image.FromStream.cs b/src/ImageSharp/Image/Image.FromStream.cs
index 90fa12e3f5..680e15aa7d 100644
--- a/src/ImageSharp/Image/Image.FromStream.cs
+++ b/src/ImageSharp/Image/Image.FromStream.cs
@@ -36,6 +36,37 @@ public static IImageFormat DetectFormat(Configuration config, Stream stream)
return WithSeekableStream(stream, s => InternalDetectFormat(s, config ?? Configuration.Default));
}
+ ///
+ /// By reading the header on the provided stream this reads the raw image information.
+ ///
+ /// The image stream to read the header from.
+ ///
+ /// Thrown if the stream is not readable nor seekable.
+ ///
+ ///
+ /// The or null if suitable info detector not found.
+ ///
+ public static IImageInfo Identify(Stream stream)
+ {
+ return Identify(null, stream);
+ }
+
+ ///
+ /// By reading the header on the provided stream this reads the raw image information.
+ ///
+ /// The configuration.
+ /// The image stream to read the header from.
+ ///
+ /// Thrown if the stream is not readable nor seekable.
+ ///
+ ///
+ /// The or null if suitable info detector not found.
+ ///
+ public static IImageInfo Identify(Configuration config, Stream stream)
+ {
+ return WithSeekableStream(stream, s => InternalIdentity(s, config ?? Configuration.Default));
+ }
+
///
/// Create a new instance of the class from the given stream.
///
diff --git a/src/ImageSharp/Image/ImageInfo.cs b/src/ImageSharp/Image/ImageInfo.cs
new file mode 100644
index 0000000000..a315ee0ed5
--- /dev/null
+++ b/src/ImageSharp/Image/ImageInfo.cs
@@ -0,0 +1,38 @@
+using SixLabors.ImageSharp.Formats;
+using SixLabors.ImageSharp.MetaData;
+
+namespace SixLabors.ImageSharp
+{
+ ///
+ /// Stores the raw image information.
+ ///
+ internal sealed class ImageInfo : IImageInfo
+ {
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The raw image pixel type information.
+ /// The width of the image in pixels.
+ /// The height of the image in pixels.
+ /// The images metadata.
+ public ImageInfo(PixelTypeInfo pixelType, int width, int height, ImageMetaData metaData)
+ {
+ this.PixelType = pixelType;
+ this.Width = width;
+ this.Height = height;
+ this.MetaData = metaData;
+ }
+
+ ///
+ public PixelTypeInfo PixelType { get; }
+
+ ///
+ public int Width { get; }
+
+ ///
+ public int Height { get; }
+
+ ///
+ public ImageMetaData MetaData { get; }
+ }
+}
\ No newline at end of file
diff --git a/src/ImageSharp/Image/Image{TPixel}.cs b/src/ImageSharp/Image/Image{TPixel}.cs
index 482971e540..be38b41f24 100644
--- a/src/ImageSharp/Image/Image{TPixel}.cs
+++ b/src/ImageSharp/Image/Image{TPixel}.cs
@@ -5,9 +5,9 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
+using System.Runtime.CompilerServices;
using SixLabors.ImageSharp.Advanced;
using SixLabors.ImageSharp.Formats;
-using SixLabors.ImageSharp.Memory;
using SixLabors.ImageSharp.MetaData;
using SixLabors.ImageSharp.PixelFormats;
@@ -17,7 +17,7 @@ namespace SixLabors.ImageSharp
/// Encapsulates an image, which consists of the pixel data for a graphics image and its attributes.
///
/// The pixel format.
- public sealed partial class Image : IDisposable, IConfigurable
+ public sealed partial class Image : IImage, IDisposable, IConfigurable
where TPixel : struct, IPixel
{
private Configuration configuration;
@@ -61,6 +61,7 @@ public Image(int width, int height)
internal Image(Configuration configuration, int width, int height, ImageMetaData metadata)
{
this.configuration = configuration ?? Configuration.Default;
+ this.PixelType = new PixelTypeInfo(Unsafe.SizeOf() * 8);
this.MetaData = metadata ?? new ImageMetaData();
this.frames = new ImageFrameCollection(this, width, height);
}
@@ -75,6 +76,7 @@ internal Image(Configuration configuration, int width, int height, ImageMetaData
internal Image(Configuration configuration, ImageMetaData metadata, IEnumerable> frames)
{
this.configuration = configuration ?? Configuration.Default;
+ this.PixelType = new PixelTypeInfo(Unsafe.SizeOf() * 8);
this.MetaData = metadata ?? new ImageMetaData();
this.frames = new ImageFrameCollection(this, frames);
@@ -85,19 +87,16 @@ internal Image(Configuration configuration, ImageMetaData metadata, IEnumerable<
///
Configuration IConfigurable.Configuration => this.configuration;
- ///
- /// Gets the width.
- ///
+ ///
+ public PixelTypeInfo PixelType { get; }
+
+ ///
public int Width => this.frames.RootFrame.Width;
- ///
- /// Gets the height.
- ///
+ ///
public int Height => this.frames.RootFrame.Height;
- ///
- /// Gets the meta data of the image.
- ///
+ ///
public ImageMetaData MetaData { get; private set; } = new ImageMetaData();
///
diff --git a/src/ImageSharp/ImageSharp.csproj b/src/ImageSharp/ImageSharp.csproj
index 8c22237cf7..1d22e59cb2 100644
--- a/src/ImageSharp/ImageSharp.csproj
+++ b/src/ImageSharp/ImageSharp.csproj
@@ -1,120 +1,120 @@
-
- A cross-platform library for the processing of image files; written in C#
- SixLabors.ImageSharp
- $(packageversion)
- 0.0.1
- Six Labors and contributors
- netstandard1.1;netstandard1.3;netstandard2.0
- true
- true
- SixLabors.ImageSharp
- SixLabors.ImageSharp
- Image Resize Crop Gif Jpg Jpeg Bitmap Png Core
- https://raw.githubusercontent.com/SixLabors/ImageSharp/master/build/icons/imagesharp-logo-128.png
- https://github.com/SixLabors/ImageSharp
- http://www.apache.org/licenses/LICENSE-2.0
- git
- https://github.com/SixLabors/ImageSharp
- false
- false
- false
- false
- false
- false
- false
- false
- false
- full
- portable
- True
- IOperation
-
-
-
-
-
-
-
-
- All
-
-
-
-
-
-
-
-
-
-
-
-
- ..\..\ImageSharp.ruleset
- SixLabors.ImageSharp
-
-
- true
-
-
-
- TextTemplatingFileGenerator
- Block8x8F.Generated.cs
-
-
- TextTemplatingFileGenerator
- Block8x8F.Generated.cs
-
-
- TextTemplatingFileGenerator
- PixelOperations{TPixel}.Generated.cs
-
-
- TextTemplatingFileGenerator
- Rgba32.PixelOperations.Generated.cs
-
-
- PorterDuffFunctions.Generated.cs
- TextTemplatingFileGenerator
-
-
- DefaultPixelBlenders.Generated.cs
- TextTemplatingFileGenerator
-
-
-
-
-
-
-
- True
- True
- Block8x8F.Generated.tt
-
-
- True
- True
- Block8x8F.Generated.tt
-
-
- True
- True
- PixelOperations{TPixel}.Generated.tt
-
-
- True
- True
- Rgba32.PixelOperations.Generated.tt
-
-
- True
- True
- DefaultPixelBlenders.Generated.tt
-
-
- True
- True
- PorterDuffFunctions.Generated.tt
-
-
+
+ A cross-platform library for the processing of image files; written in C#
+ SixLabors.ImageSharp
+ $(packageversion)
+ 0.0.1
+ Six Labors and contributors
+ netstandard1.1;netstandard1.3;netstandard2.0
+ true
+ true
+ SixLabors.ImageSharp
+ SixLabors.ImageSharp
+ Image Resize Crop Gif Jpg Jpeg Bitmap Png Core
+ https://raw.githubusercontent.com/SixLabors/ImageSharp/master/build/icons/imagesharp-logo-128.png
+ https://github.com/SixLabors/ImageSharp
+ http://www.apache.org/licenses/LICENSE-2.0
+ git
+ https://github.com/SixLabors/ImageSharp
+ false
+ false
+ false
+ false
+ false
+ false
+ false
+ false
+ false
+ full
+ portable
+ True
+ IOperation
+
+
+
+
+
+
+
+
+ All
+
+
+
+
+
+
+
+
+
+
+
+
+ ..\..\ImageSharp.ruleset
+ SixLabors.ImageSharp
+
+
+ true
+
+
+
+ TextTemplatingFileGenerator
+ Block8x8F.Generated.cs
+
+
+ TextTemplatingFileGenerator
+ Block8x8F.Generated.cs
+
+
+ TextTemplatingFileGenerator
+ PixelOperations{TPixel}.Generated.cs
+
+
+ TextTemplatingFileGenerator
+ Rgba32.PixelOperations.Generated.cs
+
+
+ PorterDuffFunctions.Generated.cs
+ TextTemplatingFileGenerator
+
+
+ DefaultPixelBlenders.Generated.cs
+ TextTemplatingFileGenerator
+
+
+
+
+
+
+
+ True
+ True
+ Block8x8F.Generated.tt
+
+
+ True
+ True
+ Block8x8F.Generated.tt
+
+
+ True
+ True
+ PixelOperations{TPixel}.Generated.tt
+
+
+ True
+ True
+ Rgba32.PixelOperations.Generated.tt
+
+
+ True
+ True
+ DefaultPixelBlenders.Generated.tt
+
+
+ True
+ True
+ PorterDuffFunctions.Generated.tt
+
+
\ No newline at end of file
diff --git a/tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs b/tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs
index 8f4b05108a..2c0121803b 100644
--- a/tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs
+++ b/tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs
@@ -8,6 +8,8 @@
namespace SixLabors.ImageSharp.Tests
{
+ using System.IO;
+
using SixLabors.ImageSharp.Formats.Bmp;
public class BmpDecoderTests : FileTestBase
@@ -35,5 +37,20 @@ public void BmpDecoder_IsNotBoundToSinglePixelType(TestImageProvider image = Image.LoadPixelData(new Rgba32[width * height], width, height))
+ {
+ using (var memoryStream = new MemoryStream())
+ {
+ image.Save(memoryStream, GetEncoder(format));
+ memoryStream.Position = 0;
+
+ var imageInfo = Image.Identify(memoryStream);
+
+ Assert.Equal(imageInfo.Width, width);
+ Assert.Equal(imageInfo.Height, height);
+ }
+ }
+ }
+
+ private static IImageEncoder GetEncoder(string format)
+ {
+ switch (format)
+ {
+ case "png":
+ return new PngEncoder();
+ case "gif":
+ return new GifEncoder();
+ case "bmp":
+ return new BmpEncoder();
+ case "jpg":
+ return new JpegEncoder();
+ default:
+ throw new ArgumentOutOfRangeException(nameof(format), format, null);
+ }
+ }
}
}
\ No newline at end of file
diff --git a/tests/ImageSharp.Tests/Formats/Gif/GifDecoderTests.cs b/tests/ImageSharp.Tests/Formats/Gif/GifDecoderTests.cs
index 76a31c1864..9a095548a7 100644
--- a/tests/ImageSharp.Tests/Formats/Gif/GifDecoderTests.cs
+++ b/tests/ImageSharp.Tests/Formats/Gif/GifDecoderTests.cs
@@ -10,6 +10,7 @@
// ReSharper disable InconsistentNaming
namespace SixLabors.ImageSharp.Tests
{
+ using System.IO;
using SixLabors.ImageSharp.Advanced;
public class GifDecoderTests
@@ -119,6 +120,20 @@ public void CanDecodeAllFrames(TestImageProvider provider)
}
}
+ [Theory]
+ [InlineData(TestImages.Gif.Cheers, 8)]
+ [InlineData(TestImages.Gif.Giphy, 8)]
+ [InlineData(TestImages.Gif.Rings, 8)]
+ [InlineData(TestImages.Gif.Trans, 8)]
+ public void DetectPixelSize(string imagePath, int expectedPixelSize)
+ {
+ TestFile testFile = TestFile.Create(imagePath);
+ using (var stream = new MemoryStream(testFile.Bytes, false))
+ {
+ Assert.Equal(expectedPixelSize, Image.Identify(stream)?.PixelType?.BitsPerPixel);
+ }
+ }
+
[Fact]
public void CanDecodeIntermingledImages()
{
diff --git a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.cs
index d529bbaeb6..cb1987aef4 100644
--- a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.cs
+++ b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.cs
@@ -385,5 +385,21 @@ public void ValidateProgressivePdfJsOutput(TestImageProvider pro
this.Output.WriteLine($"Difference for PORT: {portReport.DifferencePercentageString}");
}
}
+
+ [Theory]
+ [InlineData(TestImages.Jpeg.Progressive.Progress, 24)]
+ [InlineData(TestImages.Jpeg.Progressive.Fb, 24)]
+ [InlineData(TestImages.Jpeg.Baseline.Cmyk, 32)]
+ [InlineData(TestImages.Jpeg.Baseline.Ycck, 32)]
+ [InlineData(TestImages.Jpeg.Baseline.Jpeg400, 8)]
+ [InlineData(TestImages.Jpeg.Baseline.Snake, 24)]
+ public void DetectPixelSize(string imagePath, int expectedPixelSize)
+ {
+ TestFile testFile = TestFile.Create(imagePath);
+ using (var stream = new MemoryStream(testFile.Bytes, false))
+ {
+ Assert.Equal(expectedPixelSize, Image.Identify(stream)?.PixelType?.BitsPerPixel);
+ }
+ }
}
}
\ No newline at end of file
diff --git a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs
index d39d0651d3..248e0a5eea 100644
--- a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs
+++ b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs
@@ -184,6 +184,23 @@ public void Decode_TextEncodingSetToUnicode_TextIsReadWithCorrectEncoding()
}
}
+ [Theory]
+ [InlineData(TestImages.Png.Bpp1, 1)]
+ [InlineData(TestImages.Png.Gray4Bpp, 4)]
+ [InlineData(TestImages.Png.Palette8Bpp, 8)]
+ [InlineData(TestImages.Png.Pd, 24)]
+ [InlineData(TestImages.Png.Blur, 32)]
+ [InlineData(TestImages.Png.Rgb48Bpp, 48)]
+ [InlineData(TestImages.Png.Rgb48BppInterlaced, 48)]
+ public void DetectPixelSize(string imagePath, int expectedPixelSize)
+ {
+ TestFile testFile = TestFile.Create(imagePath);
+ using (var stream = new MemoryStream(testFile.Bytes, false))
+ {
+ Assert.Equal(expectedPixelSize, Image.Identify(stream)?.PixelType?.BitsPerPixel);
+ }
+ }
+
[Theory]
[InlineData(PngChunkTypes.Header)]
[InlineData(PngChunkTypes.Palette)]
diff --git a/tests/ImageSharp.Tests/Image/ImageDiscoverMimeType.cs b/tests/ImageSharp.Tests/Image/ImageDiscoverMimeType.cs
index 3b66579935..aefa32f469 100644
--- a/tests/ImageSharp.Tests/Image/ImageDiscoverMimeType.cs
+++ b/tests/ImageSharp.Tests/Image/ImageDiscoverMimeType.cs
@@ -38,20 +38,20 @@ public DiscoverImageFormatTests()
this.fileSystem = new Mock();
- this.LocalConfiguration = new Configuration()
+ this.LocalConfiguration = new Configuration
{
FileSystem = this.fileSystem.Object
};
this.LocalConfiguration.AddImageFormatDetector(this.localMimeTypeDetector.Object);
- TestFormat.RegisterGloablTestFormat();
+ TestFormat.RegisterGlobalTestFormat();
this.Marker = Guid.NewGuid().ToByteArray();
this.DataStream = TestFormat.GlobalTestFormat.CreateStream(this.Marker);
this.FilePath = Guid.NewGuid().ToString();
this.fileSystem.Setup(x => x.OpenRead(this.FilePath)).Returns(this.DataStream);
- TestFileSystem.RegisterGloablTestFormat();
+ TestFileSystem.RegisterGlobalTestFormat();
TestFileSystem.Global.AddFile(this.FilePath, this.DataStream);
}
@@ -83,7 +83,6 @@ public void DiscoverImageFormatFilePath_WithConfig()
Assert.Equal(localImageFormat, type);
}
-
[Fact]
public void DiscoverImageFormatStream()
{
diff --git a/tests/ImageSharp.Tests/Image/ImageLoadTests.cs b/tests/ImageSharp.Tests/Image/ImageLoadTests.cs
index f61c73636e..2c0a30b154 100644
--- a/tests/ImageSharp.Tests/Image/ImageLoadTests.cs
+++ b/tests/ImageSharp.Tests/Image/ImageLoadTests.cs
@@ -53,21 +53,21 @@ public ImageLoadTests()
this.fileSystem = new Mock();
- this.LocalConfiguration = new Configuration()
+ this.LocalConfiguration = new Configuration
{
FileSystem = this.fileSystem.Object
};
this.LocalConfiguration.AddImageFormatDetector(this.localMimeTypeDetector.Object);
this.LocalConfiguration.SetDecoder(localImageFormatMock.Object, this.localDecoder.Object);
- TestFormat.RegisterGloablTestFormat();
+ TestFormat.RegisterGlobalTestFormat();
this.Marker = Guid.NewGuid().ToByteArray();
this.DataStream = TestFormat.GlobalTestFormat.CreateStream(this.Marker);
this.FilePath = Guid.NewGuid().ToString();
this.fileSystem.Setup(x => x.OpenRead(this.FilePath)).Returns(this.DataStream);
- TestFileSystem.RegisterGloablTestFormat();
+ TestFileSystem.RegisterGlobalTestFormat();
TestFileSystem.Global.AddFile(this.FilePath, this.DataStream);
}
diff --git a/tests/ImageSharp.Tests/ImageSharp.Tests.csproj b/tests/ImageSharp.Tests/ImageSharp.Tests.csproj
index 2f45e4c83a..7e0329ef46 100644
--- a/tests/ImageSharp.Tests/ImageSharp.Tests.csproj
+++ b/tests/ImageSharp.Tests/ImageSharp.Tests.csproj
@@ -17,6 +17,7 @@
+
diff --git a/tests/ImageSharp.Tests/TestFileSystem.cs b/tests/ImageSharp.Tests/TestFileSystem.cs
index 304e8dcb86..e388b35d45 100644
--- a/tests/ImageSharp.Tests/TestFileSystem.cs
+++ b/tests/ImageSharp.Tests/TestFileSystem.cs
@@ -20,7 +20,7 @@ public class TestFileSystem : ImageSharp.IO.IFileSystem
public static TestFileSystem Global { get; } = new TestFileSystem();
- public static void RegisterGloablTestFormat()
+ public static void RegisterGlobalTestFormat()
{
Configuration.Default.FileSystem = Global;
}
diff --git a/tests/ImageSharp.Tests/TestFormat.cs b/tests/ImageSharp.Tests/TestFormat.cs
index 2683d47524..078b708dfd 100644
--- a/tests/ImageSharp.Tests/TestFormat.cs
+++ b/tests/ImageSharp.Tests/TestFormat.cs
@@ -20,15 +20,15 @@ public class TestFormat : IConfigurationModule, IImageFormat
{
public static TestFormat GlobalTestFormat { get; } = new TestFormat();
- public static void RegisterGloablTestFormat()
+ public static void RegisterGlobalTestFormat()
{
Configuration.Default.Configure(GlobalTestFormat);
}
public TestFormat()
{
- this.Encoder = new TestEncoder(this); ;
- this.Decoder = new TestDecoder(this); ;
+ this.Encoder = new TestEncoder(this);
+ this.Decoder = new TestDecoder(this);
}
public List DecodeCalls { get; } = new List();
@@ -197,7 +197,7 @@ public Image Decode(Configuration config, Stream stream) where T
config = config
});
- // TODO record this happend so we an verify it.
+ // TODO record this happend so we can verify it.
return this.testFormat.Sample();
}
@@ -219,7 +219,7 @@ public TestEncoder(TestFormat testFormat)
public void Encode(Image image, Stream stream) where TPixel : struct, IPixel
{
- // TODO record this happend so we an verify it.
+ // TODO record this happend so we can verify it.
}
}
}
diff --git a/tests/ImageSharp.Tests/TestImages.cs b/tests/ImageSharp.Tests/TestImages.cs
index 365aea04ae..c542fa8808 100644
--- a/tests/ImageSharp.Tests/TestImages.cs
+++ b/tests/ImageSharp.Tests/TestImages.cs
@@ -24,6 +24,9 @@ public static class Png
public const string Powerpoint = "Png/pp.png";
public const string SplashInterlaced = "Png/splash-interlaced.png";
public const string Interlaced = "Png/interlaced.png";
+ public const string Palette8Bpp = "Png/palette-8bpp.png";
+ public const string Bpp1 = "Png/bpp1.png";
+ public const string Gray4Bpp = "Png/gray_4bpp.png";
public const string Rgb48Bpp = "Png/rgb-48bpp.png";
public const string CalliphoraPartial = "Png/CalliphoraPartial.png";
public const string CalliphoraPartialGrayscale = "Png/CalliphoraPartialGrayscale.png";
diff --git a/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingReferenceDecoder.cs b/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingReferenceDecoder.cs
index 23ff61eb3d..0e967e9278 100644
--- a/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingReferenceDecoder.cs
+++ b/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingReferenceDecoder.cs
@@ -1,19 +1,16 @@
// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
-using System;
-using System.Drawing;
-using System.Drawing.Drawing2D;
+
using System.IO;
using SixLabors.ImageSharp.Formats;
+using SixLabors.ImageSharp.MetaData;
using SixLabors.ImageSharp.PixelFormats;
-using PixelFormat = System.Drawing.Imaging.PixelFormat;
-
namespace SixLabors.ImageSharp.Tests.TestUtilities.ReferenceCodecs
{
- public class SystemDrawingReferenceDecoder : IImageDecoder
+ public class SystemDrawingReferenceDecoder : IImageDecoder, IImageInfoDetector
{
public static SystemDrawingReferenceDecoder Instance { get; } = new SystemDrawingReferenceDecoder();
@@ -22,7 +19,7 @@ public Image Decode(Configuration configuration, Stream stream)
{
using (var sourceBitmap = new System.Drawing.Bitmap(stream))
{
- if (sourceBitmap.PixelFormat == PixelFormat.Format32bppArgb)
+ if (sourceBitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
{
return SystemDrawingBridge.FromFromArgb32SystemDrawingBitmap(sourceBitmap);
}
@@ -32,12 +29,12 @@ public Image Decode(Configuration configuration, Stream stream)
sourceBitmap.Height,
System.Drawing.Imaging.PixelFormat.Format32bppArgb))
{
- using (var g = Graphics.FromImage(convertedBitmap))
+ using (var g = System.Drawing.Graphics.FromImage(convertedBitmap))
{
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
- g.PixelOffsetMode = PixelOffsetMode.HighQuality;
+ g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
g.DrawImage(sourceBitmap, 0, 0, sourceBitmap.Width, sourceBitmap.Height);
}
@@ -45,5 +42,14 @@ public Image Decode(Configuration configuration, Stream stream)
}
}
}
+
+ public IImageInfo Identify(Configuration configuration, Stream stream)
+ {
+ using (var sourceBitmap = new System.Drawing.Bitmap(stream))
+ {
+ var pixelType = new PixelTypeInfo(System.Drawing.Image.GetPixelFormatSize(sourceBitmap.PixelFormat));
+ return new ImageInfo(pixelType, sourceBitmap.Width, sourceBitmap.Height, new ImageMetaData());
+ }
+ }
}
}
\ No newline at end of file
diff --git a/tests/Images/Input/Png/bpp1.png b/tests/Images/Input/Png/bpp1.png
new file mode 100644
index 0000000000..9ac2c1ee93
Binary files /dev/null and b/tests/Images/Input/Png/bpp1.png differ
diff --git a/tests/Images/Input/Png/gray_4bpp.png b/tests/Images/Input/Png/gray_4bpp.png
new file mode 100644
index 0000000000..6d7cd9a2f3
Binary files /dev/null and b/tests/Images/Input/Png/gray_4bpp.png differ
diff --git a/tests/Images/Input/Png/palette-8bpp.png b/tests/Images/Input/Png/palette-8bpp.png
new file mode 100644
index 0000000000..9e358d331d
Binary files /dev/null and b/tests/Images/Input/Png/palette-8bpp.png differ