diff --git a/APACHE-2.0-LICENSE.txt b/APACHE-2.0-LICENSE.txt deleted file mode 100644 index a666c6e078..0000000000 --- a/APACHE-2.0-LICENSE.txt +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2012 James South - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file diff --git a/ImageSharp.sln.DotSettings b/ImageSharp.sln.DotSettings index 1839bf2f8d..435aad73bf 100644 --- a/ImageSharp.sln.DotSettings +++ b/ImageSharp.sln.DotSettings @@ -38,10 +38,15 @@ NEXT_LINE_SHIFTED_2 1 1 + False + False False + NEVER False False + NEVER False + ALWAYS False True ON_SINGLE_LINE @@ -370,8 +375,13 @@ <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> <Policy Inspect="True" Prefix="T" Suffix="" Style="AaBb" /> <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + True + True + True + True True True + True True True \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000..2eeb57968e --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018 Six Labors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. 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 @@ namespace SixLabors.ImageSharp.Formats.Bmp 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; 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 @@ namespace SixLabors.ImageSharp.Formats.Bmp 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 @@ namespace SixLabors.ImageSharp.Formats.Bmp } } + /// + /// 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 @@ namespace SixLabors.ImageSharp.Formats.Bmp 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 @@ namespace SixLabors.ImageSharp.Formats.Gif 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 @@ namespace SixLabors.ImageSharp.Formats.Gif /// private int globalColorTableLength; - /// - /// The previous frame. - /// - private ImageFrame previousFrame; - /// /// The area to restore. /// @@ -72,12 +65,7 @@ namespace SixLabors.ImageSharp.Formats.Gif 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 @@ namespace SixLabors.ImageSharp.Formats.Gif /// /// 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 @@ namespace SixLabors.ImageSharp.Formats.Gif { 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 @@ namespace SixLabors.ImageSharp.Formats.Gif 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 @@ namespace SixLabors.ImageSharp.Formats.Gif { 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 @@ namespace SixLabors.ImageSharp.Formats.Gif /// /// 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 @@ namespace SixLabors.ImageSharp.Formats.Gif 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 @@ namespace SixLabors.ImageSharp.Formats.Gif /// /// 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 @@ namespace SixLabors.ImageSharp.Formats.Gif 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 @@ namespace SixLabors.ImageSharp.Formats.Gif 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 @@ namespace SixLabors.ImageSharp.Formats.Gif /// /// 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 @@ namespace SixLabors.ImageSharp.Formats.Gif } // 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 @@ namespace SixLabors.ImageSharp.Formats.Gif 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 @@ namespace SixLabors.ImageSharp.Formats.Gif /// 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..b7769e8955 --- /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 +{ + /// + /// Encapsulates methods used for detecting the raw image information without fully 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 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.GolangPort 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..cdc2a91972 100644 --- a/src/ImageSharp/Formats/Jpeg/GolangPort/OrigJpegDecoderCore.cs +++ b/src/ImageSharp/Formats/Jpeg/GolangPort/OrigJpegDecoderCore.cs @@ -31,6 +31,11 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.GolangPort /// 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 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.GolangPort 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 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.GolangPort 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,17 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.GolangPort 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 +648,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.GolangPort 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 @@ namespace SixLabors.ImageSharp.Formats.Jpeg 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..ed21b91bfc --- /dev/null +++ b/src/ImageSharp/Formats/PixelTypeInfo.cs @@ -0,0 +1,25 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +namespace SixLabors.ImageSharp.Formats +{ + /// + /// Contains information about the pixels that make up an images visual data. + /// + 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 @@ namespace SixLabors.ImageSharp.Formats.Png 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..5cdf80289c 100644 --- a/src/ImageSharp/Formats/Png/PngDecoderCore.cs +++ b/src/ImageSharp/Formats/Png/PngDecoderCore.cs @@ -237,7 +237,7 @@ namespace SixLabors.ImageSharp.Formats.Png 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 @@ namespace SixLabors.ImageSharp.Formats.Png } } + /// + /// 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 does not contain a 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 @@ namespace SixLabors.ImageSharp.Formats.Png 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 @@ namespace SixLabors.ImageSharp.Formats.Png } } + /// + /// 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..7355dc1fec --- /dev/null +++ b/src/ImageSharp/Image/IImage.cs @@ -0,0 +1,12 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +namespace SixLabors.ImageSharp +{ + /// + /// Encapsulates the properties and methods that describe an image. + /// + 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..25d5ec7cab --- /dev/null +++ b/src/ImageSharp/Image/IImageInfo.cs @@ -0,0 +1,35 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using SixLabors.ImageSharp.Formats; +using SixLabors.ImageSharp.MetaData; + +namespace SixLabors.ImageSharp +{ + /// + /// Encapsulates properties that descibe basic image information including dimensions, pixel type information + /// and additional metadata + /// + public interface IImageInfo + { + /// + /// Gets information about the image pixels. + /// + PixelTypeInfo PixelType { get; } + + /// + /// Gets the width. + /// + int Width { get; } + + /// + /// Gets the height. + /// + int Height { get; } + + /// + /// Gets the metadata 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..ef00ff15fd 100644 --- a/src/ImageSharp/Image/Image.Decode.cs +++ b/src/ImageSharp/Image/Image.Decode.cs @@ -79,5 +79,19 @@ namespace SixLabors.ImageSharp Image img = decoder.Decode(config, stream); return (img, format); } + + /// + /// Reads the raw image information from the specified stream. + /// + /// 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..62668dd023 100644 --- a/src/ImageSharp/Image/Image.FromStream.cs +++ b/src/ImageSharp/Image/Image.FromStream.cs @@ -36,6 +36,37 @@ namespace SixLabors.ImageSharp 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); + } + + /// + /// Reads the raw image information from the specified stream without fully decoding it. + /// + /// The configuration. + /// The image stream to read the information from. + /// + /// Thrown if the stream is not readable nor seekable. + /// + /// + /// The or null if suitable info detector is 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..6f894cb599 --- /dev/null +++ b/src/ImageSharp/Image/ImageInfo.cs @@ -0,0 +1,41 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using SixLabors.ImageSharp.Formats; +using SixLabors.ImageSharp.MetaData; + +namespace SixLabors.ImageSharp +{ + /// + /// Contains information about the image including dimensions, pixel type information and additional metadata + /// + internal sealed class ImageInfo : IImageInfo + { + /// + /// Initializes a new instance of the class. + /// + /// The 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; 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 @@ namespace SixLabors.ImageSharp 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 @@ namespace SixLabors.ImageSharp 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 @@ namespace SixLabors.ImageSharp /// 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 @@ using Xunit; namespace SixLabors.ImageSharp.Tests { + using System.IO; + using SixLabors.ImageSharp.Formats.Bmp; public class BmpDecoderTests : FileTestBase @@ -35,5 +37,20 @@ namespace SixLabors.ImageSharp.Tests image.CompareToOriginal(provider); } } + + [Theory] + [InlineData(TestImages.Bmp.Car, 24)] + [InlineData(TestImages.Bmp.F, 24)] + [InlineData(TestImages.Bmp.NegHeight, 24)] + [InlineData(TestImages.Bmp.Bit8, 8)] + [InlineData(TestImages.Bmp.Bit8Inverted, 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); + } + } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Formats/GeneralFormatTests.cs b/tests/ImageSharp.Tests/Formats/GeneralFormatTests.cs index 473bc2b523..97128e2c93 100644 --- a/tests/ImageSharp.Tests/Formats/GeneralFormatTests.cs +++ b/tests/ImageSharp.Tests/Formats/GeneralFormatTests.cs @@ -3,11 +3,19 @@ using System.IO; using SixLabors.ImageSharp.Formats; +using SixLabors.ImageSharp.Formats.Bmp; +using SixLabors.ImageSharp.Formats.Gif; +using SixLabors.ImageSharp.Formats.Jpeg; +using SixLabors.ImageSharp.Formats.Png; using SixLabors.ImageSharp.PixelFormats; using Xunit; namespace SixLabors.ImageSharp.Tests { + using System; + + + public class GeneralFormatTests : FileTestBase { [Theory] @@ -146,5 +154,56 @@ namespace SixLabors.ImageSharp.Tests } } } + + [Theory] + [InlineData(10, 10, "png")] + [InlineData(100, 100, "png")] + [InlineData(100, 10, "png")] + [InlineData(10, 100, "png")] + [InlineData(10, 10, "gif")] + [InlineData(100, 100, "gif")] + [InlineData(100, 10, "gif")] + [InlineData(10, 100, "gif")] + [InlineData(10, 10, "bmp")] + [InlineData(100, 100, "bmp")] + [InlineData(100, 10, "bmp")] + [InlineData(10, 100, "bmp")] + [InlineData(10, 10, "jpg")] + [InlineData(100, 100, "jpg")] + [InlineData(100, 10, "jpg")] + [InlineData(10, 100, "jpg")] + public void CanIdentifyImageLoadedFromBytes(int width, int height, string format) + { + using (Image 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 @@ using Xunit; // ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests { + using System.IO; using SixLabors.ImageSharp.Advanced; public class GifDecoderTests @@ -119,6 +120,20 @@ namespace SixLabors.ImageSharp.Tests } } + [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 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg 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 @@ namespace SixLabors.ImageSharp.Tests } } + [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 @@ namespace SixLabors.ImageSharp.Tests 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 @@ namespace SixLabors.ImageSharp.Tests 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 @@ namespace SixLabors.ImageSharp.Tests 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 @@ namespace SixLabors.ImageSharp.Tests 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 @@ namespace SixLabors.ImageSharp.Tests { 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 @@ namespace SixLabors.ImageSharp.Tests 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 @@ namespace SixLabors.ImageSharp.Tests 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 @@ namespace SixLabors.ImageSharp.Tests 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 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.ReferenceCodecs { 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 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.ReferenceCodecs 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 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.ReferenceCodecs } } } + + 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..cbfb46bda7 --- /dev/null +++ b/tests/Images/Input/Png/bpp1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:364e9fac6467570afe2f23e432d4f7df10dd2dd53920d4f2c743ac0f8519f1e0 +size 4403 diff --git a/tests/Images/Input/Png/gray_4bpp.png b/tests/Images/Input/Png/gray_4bpp.png new file mode 100644 index 0000000000..ff4f77fe39 --- /dev/null +++ b/tests/Images/Input/Png/gray_4bpp.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e7c6d6cbd959e84001e559702c31e313d065c9cc25808c190c4d4a1f564d4357 +size 7396 diff --git a/tests/Images/Input/Png/palette-8bpp.png b/tests/Images/Input/Png/palette-8bpp.png new file mode 100644 index 0000000000..8943fdeb37 --- /dev/null +++ b/tests/Images/Input/Png/palette-8bpp.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7bfbc244f4b0672d6a12a1f73ec062bcf762f229268b99aa4b9ffd8447512471 +size 9171