diff --git a/appveyor.yml b/appveyor.yml index d98fa9c6a..3e6b79bfc 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,18 +1,16 @@ version: 1.0.0.{build} -image: Visual Studio 2017 Preview +image: Visual Studio 2017 # prevent the double build when a branch has an active PR skip_branch_with_pr: true environment: matrix: - ### TODO: Enable the netcoreapp2.1 target when RC2 has been released! - - #- target_framework: netcoreapp2.1 - # is_32bit: False + - target_framework: netcoreapp2.1 + is_32bit: False - #- target_framework: netcoreapp2.1 - # is_32bit: True + - target_framework: netcoreapp2.1 + is_32bit: True - target_framework: netcoreapp2.0 is_32bit: False diff --git a/run-tests.ps1 b/run-tests.ps1 index d774f7a61..3218d9d67 100644 --- a/run-tests.ps1 +++ b/run-tests.ps1 @@ -75,6 +75,11 @@ else { $xunitArgs += " --fx-version 2.0.0" } + if ($targetFramework -eq "netcoreapp2.1") { + # There were issues matching the correct installed runtime if we do not specify it explicitly: + $xunitArgs += " --fx-version 2.1.0" + } + if ($is32Bit -eq "True") { $xunitArgs += " -x86" } diff --git a/src/ImageSharp.Drawing/ImageSharp.Drawing.csproj b/src/ImageSharp.Drawing/ImageSharp.Drawing.csproj index 30ca57b59..661f33e08 100644 --- a/src/ImageSharp.Drawing/ImageSharp.Drawing.csproj +++ b/src/ImageSharp.Drawing/ImageSharp.Drawing.csproj @@ -39,7 +39,8 @@ - + + All diff --git a/src/ImageSharp.Drawing/Primitives/ShapePath.cs b/src/ImageSharp.Drawing/Primitives/ShapePath.cs index 2a569f061..7a8c9e895 100644 --- a/src/ImageSharp.Drawing/Primitives/ShapePath.cs +++ b/src/ImageSharp.Drawing/Primitives/ShapePath.cs @@ -16,9 +16,8 @@ namespace SixLabors.ImageSharp.Primitives /// /// The shape. /// The pen to apply to the shape. - // TODO: SixLabors.shape will be moving to a Span/ReadOnlySpan based API shortly use ToArray for now. public ShapePath(IPath shape, IPen pen) - : base(shape.GenerateOutline(pen.StrokeWidth, pen.StrokePattern.ToArray())) + : base(shape.GenerateOutline(pen.StrokeWidth, pen.StrokePattern)) { } } diff --git a/src/ImageSharp.Drawing/Processing/Drawing/Processors/FillRegionProcessor.cs b/src/ImageSharp.Drawing/Processing/Drawing/Processors/FillRegionProcessor.cs index c81f4028b..1e968b97e 100644 --- a/src/ImageSharp.Drawing/Processing/Drawing/Processors/FillRegionProcessor.cs +++ b/src/ImageSharp.Drawing/Processing/Drawing/Processors/FillRegionProcessor.cs @@ -2,11 +2,11 @@ // Licensed under the Apache License, Version 2.0. using System; -using System.Runtime.CompilerServices; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Primitives; using SixLabors.ImageSharp.Processing.Drawing.Brushes; using SixLabors.ImageSharp.Processing.Processors; +using SixLabors.ImageSharp.Utils; using SixLabors.Memory; using SixLabors.Primitives; @@ -124,7 +124,7 @@ namespace SixLabors.ImageSharp.Processing.Drawing.Processors continue; } - QuickSort(buffer.Slice(0, pointsFound)); + QuickSort.Sort(buffer.Slice(0, pointsFound)); for (int point = 0; point < pointsFound; point += 2) { @@ -186,70 +186,5 @@ namespace SixLabors.ImageSharp.Processing.Drawing.Processors } } } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void Swap(ref float left, ref float right) - { - float tmp = left; - left = right; - right = tmp; - } - - private static void QuickSort(Span data) - { - if (data.Length < 2) - { - return; - } - else if (data.Length == 2) - { - if (data[0] > data[1]) - { - Swap(ref data[0], ref data[1]); - } - - return; - } - - QuickSort(ref data[0], 0, data.Length - 1); - } - - private static void QuickSort(ref float data0, int lo, int hi) - { - if (lo < hi) - { - int p = Partition(ref data0, lo, hi); - QuickSort(ref data0, lo, p); - QuickSort(ref data0, p + 1, hi); - } - } - - private static int Partition(ref float data0, int lo, int hi) - { - float pivot = Unsafe.Add(ref data0, lo); - int i = lo - 1; - int j = hi + 1; - while (true) - { - do - { - i = i + 1; - } - while (Unsafe.Add(ref data0, i) < pivot && i < hi); - - do - { - j = j - 1; - } - while (Unsafe.Add(ref data0, j) > pivot && j > lo); - - if (i >= j) - { - return j; - } - - Swap(ref Unsafe.Add(ref data0, i), ref Unsafe.Add(ref data0, j)); - } - } } } \ No newline at end of file diff --git a/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.Path.cs b/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.Path.cs deleted file mode 100644 index 9de73afcc..000000000 --- a/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.Path.cs +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright (c) Six Labors and contributors. -// Licensed under the Apache License, Version 2.0. - -using SixLabors.Fonts; -using SixLabors.ImageSharp.PixelFormats; -using SixLabors.ImageSharp.Processing.Drawing; -using SixLabors.ImageSharp.Processing.Drawing.Brushes; -using SixLabors.ImageSharp.Processing.Drawing.Pens; -using SixLabors.Shapes; - -namespace SixLabors.ImageSharp.Processing.Text -{ - /// - /// Adds extensions that allow the drawing of text along given paths to the type. - /// - public static partial class DrawTextExtensions - { - /// - /// Draws the text onto the the image filled via the brush. - /// - /// The type of the color. - /// The image this method extends. - /// The text. - /// The font. - /// The color. - /// The path. - /// - /// The . - /// - public static IImageProcessingContext DrawText(this IImageProcessingContext source, string text, Font font, TPixel color, IPath path) - where TPixel : struct, IPixel - => source.DrawText(TextGraphicsOptions.Default, text, font, color, path); - - /// - /// Draws the text onto the the image filled via the brush. - /// - /// The type of the color. - /// The image this method extends. - /// The options. - /// The text. - /// The font. - /// The color. - /// The path. - /// - /// The . - /// - public static IImageProcessingContext DrawText(this IImageProcessingContext source, TextGraphicsOptions options, string text, Font font, TPixel color, IPath path) - where TPixel : struct, IPixel - => source.DrawText(options, text, font, Brushes.Solid(color), null, path); - - /// - /// Draws the text onto the the image filled via the brush. - /// - /// The type of the color. - /// The image this method extends. - /// The text. - /// The font. - /// The brush. - /// The location. - /// - /// The . - /// - public static IImageProcessingContext DrawText(this IImageProcessingContext source, string text, Font font, IBrush brush, IPath path) - where TPixel : struct, IPixel - => source.DrawText(TextGraphicsOptions.Default, text, font, brush, path); - - /// - /// Draws the text onto the the image filled via the brush. - /// - /// The type of the color. - /// The image this method extends. - /// The options. - /// The text. - /// The font. - /// The brush. - /// The path. - /// - /// The . - /// - public static IImageProcessingContext DrawText(this IImageProcessingContext source, TextGraphicsOptions options, string text, Font font, IBrush brush, IPath path) - where TPixel : struct, IPixel - => source.DrawText(options, text, font, brush, null, path); - - /// - /// Draws the text onto the the image outlined via the pen. - /// - /// The type of the color. - /// The image this method extends. - /// The text. - /// The font. - /// The pen. - /// The path. - /// - /// The . - /// - public static IImageProcessingContext DrawText(this IImageProcessingContext source, string text, Font font, IPen pen, IPath path) - where TPixel : struct, IPixel - => source.DrawText(TextGraphicsOptions.Default, text, font, pen, path); - - /// - /// Draws the text onto the the image outlined via the pen. - /// - /// The type of the color. - /// The image this method extends. - /// The options. - /// The text. - /// The font. - /// The pen. - /// The path. - /// - /// The . - /// - public static IImageProcessingContext DrawText(this IImageProcessingContext source, TextGraphicsOptions options, string text, Font font, IPen pen, IPath path) - where TPixel : struct, IPixel - => source.DrawText(options, text, font, null, pen, path); - - /// - /// Draws the text onto the the image filled via the brush then outlined via the pen. - /// - /// The type of the color. - /// The image this method extends. - /// The text. - /// The font. - /// The brush. - /// The pen. - /// The path. - /// - /// The . - /// - public static IImageProcessingContext DrawText(this IImageProcessingContext source, string text, Font font, IBrush brush, IPen pen, IPath path) - where TPixel : struct, IPixel - => source.DrawText(TextGraphicsOptions.Default, text, font, brush, pen, path); - - /// - /// Draws the text onto the the image filled via the brush then outlined via the pen. - /// - /// The type of the color. - /// The image this method extends. - /// The options. - /// The text. - /// The font. - /// The brush. - /// The pen. - /// The path. - /// - /// The . - /// - public static IImageProcessingContext DrawText(this IImageProcessingContext source, TextGraphicsOptions options, string text, Font font, IBrush brush, IPen pen, IPath path) - where TPixel : struct, IPixel - { - float dpiX = DefaultTextDpi; - float dpiY = DefaultTextDpi; - - var style = new RendererOptions(font, dpiX, dpiY) - { - ApplyKerning = options.ApplyKerning, - TabWidth = options.TabWidth, - WrappingWidth = options.WrapTextWidth, - HorizontalAlignment = options.HorizontalAlignment, - VerticalAlignment = options.VerticalAlignment - }; - - IPathCollection glyphs = TextBuilder.GenerateGlyphs(text, path, style); - - var pathOptions = (GraphicsOptions)options; - if (brush != null) - { - source.Fill(pathOptions, brush, glyphs); - } - - if (pen != null) - { - source.Draw(pathOptions, pen, glyphs); - } - - return source; - } - } -} \ No newline at end of file diff --git a/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.cs b/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.cs index 8fede9693..a20d7f730 100644 --- a/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.cs +++ b/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.cs @@ -3,11 +3,10 @@ using SixLabors.Fonts; using SixLabors.ImageSharp.PixelFormats; -using SixLabors.ImageSharp.Processing.Drawing; using SixLabors.ImageSharp.Processing.Drawing.Brushes; using SixLabors.ImageSharp.Processing.Drawing.Pens; +using SixLabors.ImageSharp.Processing.Text.Processors; using SixLabors.Primitives; -using SixLabors.Shapes; namespace SixLabors.ImageSharp.Processing.Text { @@ -16,8 +15,6 @@ namespace SixLabors.ImageSharp.Processing.Text /// public static partial class DrawTextExtensions { - private static readonly int DefaultTextDpi = 72; - /// /// Draws the text onto the the image filled via the brush. /// @@ -150,33 +147,6 @@ namespace SixLabors.ImageSharp.Processing.Text /// public static IImageProcessingContext DrawText(this IImageProcessingContext source, TextGraphicsOptions options, string text, Font font, IBrush brush, IPen pen, PointF location) where TPixel : struct, IPixel - { - float dpiX = DefaultTextDpi; - float dpiY = DefaultTextDpi; - - var style = new RendererOptions(font, dpiX, dpiY, location) - { - ApplyKerning = options.ApplyKerning, - TabWidth = options.TabWidth, - WrappingWidth = options.WrapTextWidth, - HorizontalAlignment = options.HorizontalAlignment, - VerticalAlignment = options.VerticalAlignment - }; - - IPathCollection glyphs = TextBuilder.GenerateGlyphs(text, style); - - var pathOptions = (GraphicsOptions)options; - if (brush != null) - { - source.Fill(pathOptions, brush, glyphs); - } - - if (pen != null) - { - source.Draw(pathOptions, pen, glyphs); - } - - return source; - } + => source.ApplyProcessor(new DrawTextProcessor(options, text, font, brush, pen, location)); } } \ No newline at end of file diff --git a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs new file mode 100644 index 000000000..9327f9449 --- /dev/null +++ b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs @@ -0,0 +1,471 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System; +using System.Collections.Generic; +using SixLabors.Fonts; +using SixLabors.ImageSharp.Advanced; +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Processing.Drawing.Brushes; +using SixLabors.ImageSharp.Processing.Drawing.Pens; +using SixLabors.ImageSharp.Processing.Processors; +using SixLabors.ImageSharp.Utils; +using SixLabors.Memory; +using SixLabors.Primitives; +using SixLabors.Shapes; + +namespace SixLabors.ImageSharp.Processing.Text.Processors +{ + /// + /// Using the brush as a source of pixels colors blends the brush color with source. + /// + /// The pixel format. + internal class DrawTextProcessor : ImageProcessor + where TPixel : struct, IPixel + { + private CachingGlyphRenderer textRenderer; + + /// + /// Initializes a new instance of the class. + /// + /// The options + /// The text we want to render + /// The font we want to render with + /// The brush to source pixel colors from. + /// The pen to outline text with. + /// The location on the image to start drawign the text from. + public DrawTextProcessor(TextGraphicsOptions options, string text, Font font, IBrush brush, IPen pen, PointF location) + { + Guard.NotNull(text, nameof(text)); + Guard.NotNull(font, nameof(font)); + if (brush == null && pen == null) + { + throw new ArgumentNullException($"at least one of {nameof(brush)} or {nameof(pen)} must not be null"); + } + + this.Options = options; + this.Text = text; + this.Font = font; + this.Location = location; + this.Brush = brush; + this.Pen = pen; + } + + /// + /// Gets the brush. + /// + public IBrush Brush { get; } + + /// + /// Gets the options + /// + public TextGraphicsOptions Options { get; } + + /// + /// Gets the text + /// + public string Text { get; } + + /// + /// Gets the pen used for outlining the text, if Null then we will not outline + /// + public IPen Pen { get; } + + /// + /// Gets the font used to render the text. + /// + public Font Font { get; } + + /// + /// Gets the location to draw the text at. + /// + public PointF Location { get; } + + protected override void BeforeImageApply(Image source, Rectangle sourceRectangle) + { + base.BeforeImageApply(source, sourceRectangle); + + // do everythign at the image level as we are deligating the processing down to other processors + var style = new RendererOptions(this.Font, this.Options.DpiX, this.Options.DpiY, this.Location) + { + ApplyKerning = this.Options.ApplyKerning, + TabWidth = this.Options.TabWidth, + WrappingWidth = this.Options.WrapTextWidth, + HorizontalAlignment = this.Options.HorizontalAlignment, + VerticalAlignment = this.Options.VerticalAlignment + }; + + this.textRenderer = new CachingGlyphRenderer(source.GetMemoryAllocator(), this.Text.Length, this.Pen, this.Brush != null); + this.textRenderer.Options = (GraphicsOptions)this.Options; + TextRenderer.RenderTextTo(this.textRenderer, this.Text, style); + } + + protected override void AfterImageApply(Image source, Rectangle sourceRectangle) + { + base.AfterImageApply(source, sourceRectangle); + this.textRenderer?.Dispose(); + this.textRenderer = null; + } + + /// + protected override void OnFrameApply(ImageFrame source, Rectangle sourceRectangle, Configuration configuration) + { + // this is a no-op as we have processes all as an image, we should be able to pass out of before email apply a skip frames outcome + Draw(this.textRenderer.FillOperations, this.Brush); + Draw(this.textRenderer.OutlineOperations, this.Pen?.StrokeFill); + + void Draw(List operations, IBrush brush) + { + if (operations?.Count > 0) + { + using (BrushApplicator app = brush.CreateApplicator(source, sourceRectangle, this.textRenderer.Options)) + { + foreach (DrawingOperation operation in operations) + { + Buffer2D buffer = operation.Map; + int startY = operation.Location.Y; + int startX = operation.Location.X; + int offSetSpan = 0; + if (startX < 0) + { + offSetSpan = -startX; + startX = 0; + } + + int fistRow = 0; + if (startY < 0) + { + fistRow = -startY; + } + + int end = operation.Map.Height; + + int maxHeight = source.Height - startY; + end = Math.Min(end, maxHeight); + + for (int row = fistRow; row < end; row++) + { + int y = startY + row; + Span span = buffer.GetRowSpan(row).Slice(offSetSpan); + app.Apply(span, startX, y); + } + } + } + } + } + } + + private struct DrawingOperation + { + public Buffer2D Map { get; set; } + + public Point Location { get; set; } + } + + private class CachingGlyphRenderer : IGlyphRenderer, IDisposable + { + private PathBuilder builder; + + private Point currentRenderPosition = default; + private GlyphRendererParameters currentGlyphRenderParams = default; + private int offset = 0; + private PointF currentPoint = default(PointF); + + private readonly Dictionary glyphData = new Dictionary(); + + private bool renderOutline = false; + private bool renderFill = false; + private bool raterizationRequired = false; + + public CachingGlyphRenderer(MemoryAllocator memoryAllocator, int size, IPen pen, bool renderFill) + { + this.MemoryAllocator = memoryAllocator; + this.Pen = pen; + this.renderFill = renderFill; + this.renderOutline = pen != null; + this.offset = 2; + if (this.renderFill) + { + this.FillOperations = new List(size); + } + + if (this.renderOutline) + { + this.offset = (int)MathF.Ceiling((pen.StrokeWidth * 2) + 2); + this.OutlineOperations = new List(size); + } + + this.builder = new PathBuilder(); + } + + public List FillOperations { get; } + + public List OutlineOperations { get; } + + public MemoryAllocator MemoryAllocator { get; internal set; } + + public IPen Pen { get; internal set; } + + public GraphicsOptions Options { get; internal set; } + + public void BeginFigure() + { + this.builder.StartFigure(); + } + + public bool BeginGlyph(RectangleF bounds, GlyphRendererParameters paramters) + { + this.currentRenderPosition = Point.Truncate(bounds.Location); + + // we have offset our rendering origion a little bit down to prevent edge cropping, move the draw origin up to compensate + this.currentRenderPosition = new Point(this.currentRenderPosition.X - this.offset, this.currentRenderPosition.Y - this.offset); + this.currentGlyphRenderParams = paramters; + if (this.glyphData.ContainsKey(paramters)) + { + // we have already drawn the glyph vectors skip trying again + this.raterizationRequired = false; + return false; + } + + // we check to see if we have a render cache and if we do then we render else + this.builder.Clear(); + + // ensure all glyphs render around [zero, zero] so offset negative root positions so when we draw the glyph we can offet it back + this.builder.SetOrigin(new PointF(-(int)bounds.X + this.offset, -(int)bounds.Y + this.offset)); + + this.raterizationRequired = true; + return true; + } + + public void BeginText(RectangleF bounds) + { + // not concerned about this one + this.OutlineOperations?.Clear(); + this.FillOperations?.Clear(); + } + + public void CubicBezierTo(PointF secondControlPoint, PointF thirdControlPoint, PointF point) + { + this.builder.AddBezier(this.currentPoint, secondControlPoint, thirdControlPoint, point); + this.currentPoint = point; + } + + public void Dispose() + { + foreach (KeyValuePair kv in this.glyphData) + { + kv.Value.Dispose(); + } + + this.glyphData.Clear(); + } + + public void EndFigure() + { + this.builder.CloseFigure(); + } + + public void EndGlyph() + { + GlyphRenderData renderData = default; + + // has the glyoh been rendedered already???? + if (this.raterizationRequired) + { + IPath path = this.builder.Build(); + + if (this.renderFill) + { + renderData.FillMap = this.Render(path); + } + + if (this.renderOutline) + { + if (this.Pen.StrokePattern.Length == 0) + { + path = path.GenerateOutline(this.Pen.StrokeWidth); + } + else + { + path = path.GenerateOutline(this.Pen.StrokeWidth, this.Pen.StrokePattern); + } + + renderData.OutlineMap = this.Render(path); + } + + this.glyphData[this.currentGlyphRenderParams] = renderData; + } + else + { + renderData = this.glyphData[this.currentGlyphRenderParams]; + } + + if (this.renderFill) + { + this.FillOperations.Add(new DrawingOperation + { + Location = this.currentRenderPosition, + Map = renderData.FillMap + }); + } + + if (this.renderOutline) + { + this.OutlineOperations.Add(new DrawingOperation + { + Location = this.currentRenderPosition, + Map = renderData.OutlineMap + }); + } + } + + private Buffer2D Render(IPath path) + { + Size size = Rectangle.Ceiling(path.Bounds).Size; + size = new Size(size.Width + (this.offset * 2), size.Height + (this.offset * 2)); + + float subpixelCount = 4; + float offset = 0.5f; + if (this.Options.Antialias) + { + offset = 0f; // we are antialising skip offsetting as real antalising should take care of offset. + subpixelCount = this.Options.AntialiasSubpixelDepth; + if (subpixelCount < 4) + { + subpixelCount = 4; + } + } + + // take the path inside the path builder, scan thing and generate a Buffer2d representing the glyph and cache it. + Buffer2D fullBuffer = this.MemoryAllocator.Allocate2D(size.Width + 1, size.Height + 1, true); + + using (IBuffer bufferBacking = this.MemoryAllocator.Allocate(path.MaxIntersections)) + using (IBuffer rowIntersectionBuffer = this.MemoryAllocator.Allocate(size.Width)) + { + float subpixelFraction = 1f / subpixelCount; + float subpixelFractionPoint = subpixelFraction / subpixelCount; + + for (int y = 0; y <= size.Height; y++) + { + Span scanline = fullBuffer.GetRowSpan(y); + bool scanlineDirty = false; + float yPlusOne = y + 1; + + for (float subPixel = (float)y; subPixel < yPlusOne; subPixel += subpixelFraction) + { + var start = new PointF(path.Bounds.Left - 1, subPixel); + var end = new PointF(path.Bounds.Right + 1, subPixel); + Span intersectionSpan = rowIntersectionBuffer.GetSpan(); + Span buffer = bufferBacking.GetSpan(); + int pointsFound = path.FindIntersections(start, end, intersectionSpan); + + if (pointsFound == 0) + { + // nothing on this line skip + continue; + } + + for (int i = 0; i < pointsFound && i < intersectionSpan.Length; i++) + { + buffer[i] = intersectionSpan[i].X; + } + + QuickSort.Sort(buffer.Slice(0, pointsFound)); + + for (int point = 0; point < pointsFound; point += 2) + { + // points will be paired up + float scanStart = buffer[point]; + float scanEnd = buffer[point + 1]; + int startX = (int)MathF.Floor(scanStart + offset); + int endX = (int)MathF.Floor(scanEnd + offset); + + if (startX >= 0 && startX < scanline.Length) + { + for (float x = scanStart; x < startX + 1; x += subpixelFraction) + { + scanline[startX] += subpixelFractionPoint; + scanlineDirty = true; + } + } + + if (endX >= 0 && endX < scanline.Length) + { + for (float x = endX; x < scanEnd; x += subpixelFraction) + { + scanline[endX] += subpixelFractionPoint; + scanlineDirty = true; + } + } + + int nextX = startX + 1; + endX = Math.Min(endX, scanline.Length); // reduce to end to the right edge + nextX = Math.Max(nextX, 0); + for (int x = nextX; x < endX; x++) + { + scanline[x] += subpixelFraction; + scanlineDirty = true; + } + } + } + + if (scanlineDirty) + { + if (!this.Options.Antialias) + { + for (int x = 0; x < size.Width; x++) + { + if (scanline[x] >= 0.5) + { + scanline[x] = 1; + } + else + { + scanline[x] = 0; + } + } + } + } + } + } + + return fullBuffer; + } + + public void EndText() + { + } + + public void LineTo(PointF point) + { + this.builder.AddLine(this.currentPoint, point); + this.currentPoint = point; + } + + public void MoveTo(PointF point) + { + this.builder.StartFigure(); + this.currentPoint = point; + } + + public void QuadraticBezierTo(PointF secondControlPoint, PointF point) + { + this.builder.AddBezier(this.currentPoint, secondControlPoint, point); + this.currentPoint = point; + } + + private struct GlyphRenderData : IDisposable + { + public Buffer2D FillMap; + + public Buffer2D OutlineMap; + + public void Dispose() + { + this.FillMap?.Dispose(); + this.OutlineMap?.Dispose(); + } + } + } + } +} \ No newline at end of file diff --git a/src/ImageSharp.Drawing/Processing/Text/TextGraphicsOptions.cs b/src/ImageSharp.Drawing/Processing/Text/TextGraphicsOptions.cs index bba473ddb..aaa6dea56 100644 --- a/src/ImageSharp.Drawing/Processing/Text/TextGraphicsOptions.cs +++ b/src/ImageSharp.Drawing/Processing/Text/TextGraphicsOptions.cs @@ -11,6 +11,8 @@ namespace SixLabors.ImageSharp.Processing.Text /// public struct TextGraphicsOptions { + private const int DefaultTextDpi = 72; + /// /// Represents the default . /// @@ -26,11 +28,16 @@ namespace SixLabors.ImageSharp.Processing.Text private float? tabWidth; + private float? dpiX; + + private float? dpiY; + private PixelBlenderMode blenderMode; private float wrapTextWidth; private HorizontalAlignment? horizontalAlignment; + private VerticalAlignment? verticalAlignment; /// @@ -49,6 +56,8 @@ namespace SixLabors.ImageSharp.Processing.Text this.blenderMode = PixelBlenderMode.Normal; this.blendPercentage = 1; this.antialias = enableAntialiasing; + this.dpiX = DefaultTextDpi; + this.dpiY = DefaultTextDpi; } /// @@ -90,6 +99,16 @@ namespace SixLabors.ImageSharp.Processing.Text /// public float WrapTextWidth { get => this.wrapTextWidth; set => this.wrapTextWidth = value; } + /// + /// Gets or sets a value indicating the DPI to render text along the X axis. + /// + public float DpiX { get => this.dpiX ?? DefaultTextDpi; set => this.dpiX = value; } + + /// + /// Gets or sets a value indicating the DPI to render text along the Y axis. + /// + public float DpiY { get => this.dpiY ?? DefaultTextDpi; set => this.dpiY = value; } + /// /// Gets or sets a value indicating how to align the text relative to the rendering space. /// If is greater than zero it will align relative to the space diff --git a/src/ImageSharp.Drawing/Utils/QuickSort.cs b/src/ImageSharp.Drawing/Utils/QuickSort.cs new file mode 100644 index 000000000..ca1da5505 --- /dev/null +++ b/src/ImageSharp.Drawing/Utils/QuickSort.cs @@ -0,0 +1,84 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System; +using System.Runtime.CompilerServices; + +namespace SixLabors.ImageSharp.Utils +{ + /// + /// Optimized quick sort implementation for Span{float} input + /// + internal class QuickSort + { + /// + /// Sorts the elements of in ascending order + /// + /// The items to sort + public static void Sort(Span data) + { + if (data.Length < 2) + { + return; + } + + if (data.Length == 2) + { + if (data[0] > data[1]) + { + Swap(ref data[0], ref data[1]); + } + + return; + } + + Sort(ref data[0], 0, data.Length - 1); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Swap(ref float left, ref float right) + { + float tmp = left; + left = right; + right = tmp; + } + + private static void Sort(ref float data0, int lo, int hi) + { + if (lo < hi) + { + int p = Partition(ref data0, lo, hi); + Sort(ref data0, lo, p); + Sort(ref data0, p + 1, hi); + } + } + + private static int Partition(ref float data0, int lo, int hi) + { + float pivot = Unsafe.Add(ref data0, lo); + int i = lo - 1; + int j = hi + 1; + while (true) + { + do + { + i = i + 1; + } + while (Unsafe.Add(ref data0, i) < pivot && i < hi); + + do + { + j = j - 1; + } + while (Unsafe.Add(ref data0, j) > pivot && j > lo); + + if (i >= j) + { + return j; + } + + Swap(ref Unsafe.Add(ref data0, i), ref Unsafe.Add(ref data0, j)); + } + } + } +} diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Adapt.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Adapt.cs index 80f9e6789..4bb537aeb 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Adapt.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Adapt.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. using System; -using SixLabors.ImageSharp.ColorSpaces; using SixLabors.ImageSharp.ColorSpaces.Conversion.Implementation.RgbColorSapce; namespace SixLabors.ImageSharp.ColorSpaces.Conversion @@ -21,9 +20,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The adapted color public CieXyz Adapt(CieXyz color, CieXyz sourceWhitePoint) { - Guard.NotNull(color, nameof(color)); - Guard.NotNull(sourceWhitePoint, nameof(sourceWhitePoint)); - if (!this.IsChromaticAdaptationPerformed) { throw new InvalidOperationException("Cannot perform chromatic adaptation, provide a chromatic adaptation method and white point."); @@ -39,8 +35,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The adapted color public CieLab Adapt(CieLab color) { - Guard.NotNull(color, nameof(color)); - if (!this.IsChromaticAdaptationPerformed) { throw new InvalidOperationException("Cannot perform chromatic adaptation, provide a chromatic adaptation method and white point."); @@ -62,8 +56,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The adapted color public CieLch Adapt(CieLch color) { - Guard.NotNull(color, nameof(color)); - if (!this.IsChromaticAdaptationPerformed) { throw new InvalidOperationException("Cannot perform chromatic adaptation, provide a chromatic adaptation method and white point."); @@ -85,8 +77,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The adapted color public CieLchuv Adapt(CieLchuv color) { - Guard.NotNull(color, nameof(color)); - if (!this.IsChromaticAdaptationPerformed) { throw new InvalidOperationException("Cannot perform chromatic adaptation, provide a chromatic adaptation method and white point."); @@ -108,8 +98,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The adapted color public CieLuv Adapt(CieLuv color) { - Guard.NotNull(color, nameof(color)); - if (!this.IsChromaticAdaptationPerformed) { throw new InvalidOperationException("Cannot perform chromatic adaptation, provide a chromatic adaptation method and white point."); @@ -131,8 +119,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The adapted color public HunterLab Adapt(HunterLab color) { - Guard.NotNull(color, nameof(color)); - if (!this.IsChromaticAdaptationPerformed) { throw new InvalidOperationException("Cannot perform chromatic adaptation, provide a chromatic adaptation method and white point."); @@ -154,8 +140,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The adapted color public LinearRgb Adapt(LinearRgb color) { - Guard.NotNull(color, nameof(color)); - if (!this.IsChromaticAdaptationPerformed) { throw new InvalidOperationException("Cannot perform chromatic adaptation, provide a chromatic adaptation method and white point."); @@ -185,8 +169,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The adapted color public Rgb Adapt(Rgb color) { - Guard.NotNull(color, nameof(color)); - LinearRgb linearInput = this.ToLinearRgb(color); LinearRgb linearOutput = this.Adapt(linearInput); return this.ToRgb(linearOutput); diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLab.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLab.cs index 3f5c2e246..16e3ec707 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLab.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLab.cs @@ -23,8 +23,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLab ToCieLab(CieLch color) { - Guard.NotNull(color, nameof(color)); - // Conversion (perserving white point) CieLab unadapted = CieLchToCieLabConverter.Convert(color); @@ -77,8 +75,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLab ToCieLab(CieXyz color) { - Guard.NotNull(color, nameof(color)); - // Adaptation CieXyz adapted = !this.WhitePoint.Equals(this.TargetLabWhitePoint) && this.IsChromaticAdaptationPerformed ? this.ChromaticAdaptation.Transform(color, this.WhitePoint, this.TargetLabWhitePoint) @@ -96,8 +92,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLab ToCieLab(Cmyk color) { - Guard.NotNull(color, nameof(color)); - CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLab(xyzColor); } @@ -120,8 +114,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLab ToCieLab(Hsv color) { - Guard.NotNull(color, nameof(color)); - CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLab(xyzColor); } diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLch.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLch.cs index 469875c02..b13580209 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLch.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLch.cs @@ -80,8 +80,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLch ToCieLch(Cmyk color) { - Guard.NotNull(color, nameof(color)); - CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLch(xyzColor); } diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieXyy.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieXyy.cs index 31e1e218e..5f6aaea6b 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieXyy.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieXyy.cs @@ -19,8 +19,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(CieLab color) { - Guard.NotNull(color, nameof(color)); - var xyzColor = this.ToCieXyz(color); return this.ToCieXyy(xyzColor); @@ -33,8 +31,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(CieLch color) { - Guard.NotNull(color, nameof(color)); - var xyzColor = this.ToCieXyz(color); return this.ToCieXyy(xyzColor); @@ -47,8 +43,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(CieLchuv color) { - Guard.NotNull(color, nameof(color)); - var xyzColor = this.ToCieXyz(color); return this.ToCieXyy(xyzColor); @@ -61,8 +55,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(CieLuv color) { - Guard.NotNull(color, nameof(color)); - var xyzColor = this.ToCieXyz(color); return this.ToCieXyy(xyzColor); @@ -75,8 +67,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(CieXyz color) { - Guard.NotNull(color, nameof(color)); - return CieXyzAndCieXyyConverter.Convert(color); } @@ -87,8 +77,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(Cmyk color) { - Guard.NotNull(color, nameof(color)); - var xyzColor = this.ToCieXyz(color); return this.ToCieXyy(xyzColor); @@ -101,8 +89,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(Hsl color) { - Guard.NotNull(color, nameof(color)); - var xyzColor = this.ToCieXyz(color); return this.ToCieXyy(xyzColor); @@ -115,8 +101,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(Hsv color) { - Guard.NotNull(color, nameof(color)); - var xyzColor = this.ToCieXyz(color); return this.ToCieXyy(xyzColor); @@ -129,8 +113,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(HunterLab color) { - Guard.NotNull(color, nameof(color)); - var xyzColor = this.ToCieXyz(color); return this.ToCieXyy(xyzColor); @@ -143,8 +125,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(LinearRgb color) { - Guard.NotNull(color, nameof(color)); - var xyzColor = this.ToCieXyz(color); return this.ToCieXyy(xyzColor); @@ -157,8 +137,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(Lms color) { - Guard.NotNull(color, nameof(color)); - var xyzColor = this.ToCieXyz(color); return this.ToCieXyy(xyzColor); @@ -171,8 +149,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(Rgb color) { - Guard.NotNull(color, nameof(color)); - var xyzColor = this.ToCieXyz(color); return this.ToCieXyy(xyzColor); @@ -185,8 +161,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(YCbCr color) { - Guard.NotNull(color, nameof(color)); - var xyzColor = this.ToCieXyz(color); return this.ToCieXyy(xyzColor); diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieXyz.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieXyz.cs index e6847beaf..cd3f7f3c8 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieXyz.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieXyz.cs @@ -1,7 +1,6 @@ // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -using SixLabors.ImageSharp.ColorSpaces; using SixLabors.ImageSharp.ColorSpaces.Conversion.Implementation.CieLabColorSapce; using SixLabors.ImageSharp.ColorSpaces.Conversion.Implementation.CieLuvColorSapce; using SixLabors.ImageSharp.ColorSpaces.Conversion.Implementation.HunterLabColorSapce; @@ -29,8 +28,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyz ToCieXyz(CieLab color) { - Guard.NotNull(color, nameof(color)); - // Conversion CieXyz unadapted = CieLabToCieXyzConverter.Convert(color); @@ -49,8 +46,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyz ToCieXyz(CieLch color) { - Guard.NotNull(color, nameof(color)); - // Conversion to Lab CieLab labColor = CieLchToCieLabConverter.Convert(color); @@ -65,8 +60,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyz ToCieXyz(CieLchuv color) { - Guard.NotNull(color, nameof(color)); - // Conversion to Luv CieLuv luvColor = CieLchuvToCieLuvConverter.Convert(color); @@ -81,8 +74,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyz ToCieXyz(CieLuv color) { - Guard.NotNull(color, nameof(color)); - // Conversion CieXyz unadapted = CieLuvToCieXyzConverter.Convert(color); @@ -101,8 +92,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyz ToCieXyz(CieXyy color) { - Guard.NotNull(color, nameof(color)); - // Conversion return CieXyzAndCieXyyConverter.Convert(color); } @@ -114,8 +103,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyz ToCieXyz(Cmyk color) { - Guard.NotNull(color, nameof(color)); - // Conversion var rgb = this.ToRgb(color); @@ -129,8 +116,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyz ToCieXyz(Hsl color) { - Guard.NotNull(color, nameof(color)); - // Conversion var rgb = this.ToRgb(color); @@ -144,8 +129,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyz ToCieXyz(Hsv color) { - Guard.NotNull(color, nameof(color)); - // Conversion var rgb = this.ToRgb(color); @@ -159,8 +142,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyz ToCieXyz(HunterLab color) { - Guard.NotNull(color, nameof(color)); - // Conversion CieXyz unadapted = HunterLabToCieXyzConverter.Convert(color); @@ -179,8 +160,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyz ToCieXyz(LinearRgb color) { - Guard.NotNull(color, nameof(color)); - // Conversion LinearRgbToCieXyzConverter converter = this.GetLinearRgbToCieXyzConverter(color.WorkingSpace); CieXyz unadapted = converter.Convert(color); @@ -198,8 +177,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyz ToCieXyz(Lms color) { - Guard.NotNull(color, nameof(color)); - // Conversion return this.cachedCieXyzAndLmsConverter.Convert(color); } @@ -211,8 +188,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyz ToCieXyz(Rgb color) { - Guard.NotNull(color, nameof(color)); - // Conversion LinearRgb linear = RgbToLinearRgbConverter.Convert(color); return this.ToCieXyz(linear); @@ -225,8 +200,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyz ToCieXyz(YCbCr color) { - Guard.NotNull(color, nameof(color)); - // Conversion var rgb = this.ToRgb(color); diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Hsv.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Hsv.cs index 640461505..0aa644567 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Hsv.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Hsv.cs @@ -1,7 +1,6 @@ // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -using SixLabors.ImageSharp.ColorSpaces; using SixLabors.ImageSharp.ColorSpaces.Conversion.Implementation.HsvColorSapce; namespace SixLabors.ImageSharp.ColorSpaces.Conversion @@ -20,8 +19,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsv ToHsv(CieLab color) { - Guard.NotNull(color, nameof(color)); - var xyzColor = this.ToCieXyz(color); return this.ToHsv(xyzColor); @@ -34,8 +31,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsv ToHsv(CieLch color) { - Guard.NotNull(color, nameof(color)); - var xyzColor = this.ToCieXyz(color); return this.ToHsv(xyzColor); @@ -48,8 +43,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsv ToHsv(CieLchuv color) { - Guard.NotNull(color, nameof(color)); - var xyzColor = this.ToCieXyz(color); return this.ToHsv(xyzColor); @@ -62,8 +55,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsv ToHsv(CieLuv color) { - Guard.NotNull(color, nameof(color)); - var xyzColor = this.ToCieXyz(color); return this.ToHsv(xyzColor); @@ -76,8 +67,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsv ToHsv(CieXyy color) { - Guard.NotNull(color, nameof(color)); - var xyzColor = this.ToCieXyz(color); return this.ToHsv(xyzColor); @@ -90,8 +79,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsv ToHsv(CieXyz color) { - Guard.NotNull(color, nameof(color)); - var rgb = this.ToRgb(color); return HsvAndRgbConverter.Convert(rgb); @@ -104,8 +91,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsv ToHsv(Cmyk color) { - Guard.NotNull(color, nameof(color)); - var rgb = this.ToRgb(color); return HsvAndRgbConverter.Convert(rgb); @@ -118,8 +103,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsv ToHsv(Hsl color) { - Guard.NotNull(color, nameof(color)); - var rgb = this.ToRgb(color); return HsvAndRgbConverter.Convert(rgb); @@ -132,8 +115,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsv ToHsv(HunterLab color) { - Guard.NotNull(color, nameof(color)); - var xyzColor = this.ToCieXyz(color); return this.ToHsv(xyzColor); @@ -146,8 +127,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsv ToHsv(LinearRgb color) { - Guard.NotNull(color, nameof(color)); - var rgb = this.ToRgb(color); return HsvAndRgbConverter.Convert(rgb); @@ -160,8 +139,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsv ToHsv(Lms color) { - Guard.NotNull(color, nameof(color)); - var xyzColor = this.ToCieXyz(color); return this.ToHsv(xyzColor); @@ -174,8 +151,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsv ToHsv(Rgb color) { - Guard.NotNull(color, nameof(color)); - return HsvAndRgbConverter.Convert(color); } @@ -186,8 +161,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsv ToHsv(YCbCr color) { - Guard.NotNull(color, nameof(color)); - var rgb = this.ToRgb(color); return HsvAndRgbConverter.Convert(rgb); diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.LinearRgb.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.LinearRgb.cs index 91c78b3ea..92d2cd861 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.LinearRgb.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.LinearRgb.cs @@ -115,8 +115,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public LinearRgb ToLinearRgb(Hsv color) { - Guard.NotNull(color, nameof(color)); - var rgb = this.ToRgb(color); return this.ToLinearRgb(rgb); } diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Rgb.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Rgb.cs index 45beecf66..b609934e9 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Rgb.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Rgb.cs @@ -110,8 +110,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Rgb ToRgb(Hsl color) { - Guard.NotNull(color, nameof(color)); - // Conversion return HslAndRgbConverter.Convert(color); } diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/CieLuv/CieXyzToCieLuvConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/CieLuv/CieXyzToCieLuvConverter.cs index 709d8d426..e1c5dde4f 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/CieLuv/CieXyzToCieLuvConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/CieLuv/CieXyzToCieLuvConverter.cs @@ -44,8 +44,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion.Implementation.CieLuvColor [MethodImpl(MethodImplOptions.AggressiveInlining)] public CieLuv Convert(CieXyz input) { - DebugGuard.NotNull(input, nameof(input)); - // Conversion algorithm described here: http://www.brucelindbloom.com/index.html?Eqn_XYZ_to_Luv.html float yr = input.Y / this.LuvWhitePoint.Y; float up = ComputeUp(input); diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/CieXyy/CieXyzAndCieXyyConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/CieXyy/CieXyzAndCieXyyConverter.cs index bb7d6bb3f..7dfc577dc 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/CieXyy/CieXyzAndCieXyyConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/CieXyy/CieXyzAndCieXyyConverter.cs @@ -16,8 +16,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion.Implementation.CieXyyColor [MethodImpl(MethodImplOptions.AggressiveInlining)] public CieXyy Convert(CieXyz input) { - DebugGuard.NotNull(input, nameof(input)); - float x = input.X / (input.X + input.Y + input.Z); float y = input.Y / (input.X + input.Y + input.Z); @@ -33,8 +31,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion.Implementation.CieXyyColor [MethodImpl(MethodImplOptions.AggressiveInlining)] public CieXyz Convert(CieXyy input) { - DebugGuard.NotNull(input, nameof(input)); - if (MathF.Abs(input.Y) < Constants.Epsilon) { return new CieXyz(0, 0, input.Yl); diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Hsl/HslAndRgbConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Hsl/HslAndRgbConverter.cs index 2bdbbceca..7983b6ce4 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Hsl/HslAndRgbConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Hsl/HslAndRgbConverter.cs @@ -16,8 +16,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion.Implementation.HslColorSap [MethodImpl(MethodImplOptions.AggressiveInlining)] public Rgb Convert(Hsl input) { - DebugGuard.NotNull(input, nameof(input)); - float rangedH = input.H / 360F; float r = 0; float g = 0; @@ -49,8 +47,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion.Implementation.HslColorSap [MethodImpl(MethodImplOptions.AggressiveInlining)] public Hsl Convert(Rgb input) { - DebugGuard.NotNull(input, nameof(input)); - float r = input.R; float g = input.G; float b = input.B; diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Hsv/HsvAndRgbConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Hsv/HsvAndRgbConverter.cs index 981b8f3ab..c46d8f26b 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Hsv/HsvAndRgbConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Hsv/HsvAndRgbConverter.cs @@ -16,8 +16,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion.Implementation.HsvColorSap [MethodImpl(MethodImplOptions.AggressiveInlining)] public Rgb Convert(Hsv input) { - DebugGuard.NotNull(input, nameof(input)); - float s = input.S; float v = input.V; @@ -81,8 +79,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion.Implementation.HsvColorSap [MethodImpl(MethodImplOptions.AggressiveInlining)] public Hsv Convert(Rgb input) { - DebugGuard.NotNull(input, nameof(input)); - float r = input.R; float g = input.G; float b = input.B; diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/HunterLab/CieXyzAndHunterLabConverterBase.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/HunterLab/CieXyzAndHunterLabConverterBase.cs index 2d4e3b0e7..ebf75e0d5 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/HunterLab/CieXyzAndHunterLabConverterBase.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/HunterLab/CieXyzAndHunterLabConverterBase.cs @@ -34,8 +34,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion.Implementation.HunterLabCo [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float ComputeKb(CieXyz whitePoint) { - DebugGuard.NotNull(whitePoint, nameof(whitePoint)); - if (whitePoint == Illuminants.C) { return 70F; diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/HunterLab/CieXyzToHunterLabConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/HunterLab/CieXyzToHunterLabConverter.cs index 309663796..58363ea2b 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/HunterLab/CieXyzToHunterLabConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/HunterLab/CieXyzToHunterLabConverter.cs @@ -33,18 +33,12 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion.Implementation.HunterLabCo /// /// Gets the target reference white. When not set, is used. /// - public CieXyz HunterLabWhitePoint - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get; - } + public CieXyz HunterLabWhitePoint { get; } /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public HunterLab Convert(CieXyz input) { - DebugGuard.NotNull(input, nameof(input)); - // Conversion algorithm described here: http://en.wikipedia.org/wiki/Lab_color_space#Hunter_Lab float x = input.X, y = input.Y, z = input.Z; float xn = this.HunterLabWhitePoint.X, yn = this.HunterLabWhitePoint.Y, zn = this.HunterLabWhitePoint.Z; diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Rgb/CieXyzToLinearRgbConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Rgb/CieXyzToLinearRgbConverter.cs index fd76a30fb..2f52c2074 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Rgb/CieXyzToLinearRgbConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Rgb/CieXyzToLinearRgbConverter.cs @@ -38,8 +38,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion.Implementation.RgbColorSap /// public LinearRgb Convert(CieXyz input) { - DebugGuard.NotNull(input, nameof(input)); - Matrix4x4.Invert(this.conversionMatrix, out Matrix4x4 inverted); Vector3 vector = Vector3.Transform(input.Vector, inverted); return new LinearRgb(vector, this.TargetWorkingSpace); diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Rgb/LinearRgbToCieXyzConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Rgb/LinearRgbToCieXyzConverter.cs index bf36e252a..0746c78c3 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Rgb/LinearRgbToCieXyzConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Rgb/LinearRgbToCieXyzConverter.cs @@ -38,7 +38,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion.Implementation.RgbColorSap /// public CieXyz Convert(LinearRgb input) { - DebugGuard.NotNull(input, nameof(input)); DebugGuard.IsTrue(input.WorkingSpace.Equals(this.SourceWorkingSpace), nameof(input.WorkingSpace), "Input and source working spaces must be equal."); Vector3 vector = Vector3.Transform(input.Vector, this.conversionMatrix); diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Rgb/LinearRgbToRgbConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Rgb/LinearRgbToRgbConverter.cs index 29ea0f314..3b70c02af 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Rgb/LinearRgbToRgbConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Rgb/LinearRgbToRgbConverter.cs @@ -13,8 +13,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion.Implementation.RgbColorSap /// public Rgb Convert(LinearRgb input) { - DebugGuard.NotNull(input, nameof(input)); - Vector3 vector = input.Vector; vector.X = input.WorkingSpace.Companding.Compress(vector.X); vector.Y = input.WorkingSpace.Companding.Compress(vector.Y); diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/YCbCr/YCbCrAndRgbConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/YCbCr/YCbCrAndRgbConverter.cs index aa9668b82..99149a592 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/YCbCr/YCbCrAndRgbConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/YCbCr/YCbCrAndRgbConverter.cs @@ -19,8 +19,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion.Implementation.YCbCrColorS [MethodImpl(MethodImplOptions.AggressiveInlining)] public Rgb Convert(YCbCr input) { - DebugGuard.NotNull(input, nameof(input)); - float y = input.Y; float cb = input.Cb - 128F; float cr = input.Cr - 128F; @@ -36,8 +34,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion.Implementation.YCbCrColorS [MethodImpl(MethodImplOptions.AggressiveInlining)] public YCbCr Convert(Rgb input) { - DebugGuard.NotNull(input, nameof(input)); - Vector3 rgb = input.Vector * MaxBytes; float r = rgb.X; float g = rgb.Y; diff --git a/src/ImageSharp/Common/Extensions/StreamExtensions.cs b/src/ImageSharp/Common/Extensions/StreamExtensions.cs index 7a9a34ac1..d11ba8ca5 100644 --- a/src/ImageSharp/Common/Extensions/StreamExtensions.cs +++ b/src/ImageSharp/Common/Extensions/StreamExtensions.cs @@ -1,7 +1,7 @@ // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -using System.Buffers; +using System; using System.IO; namespace SixLabors.ImageSharp @@ -11,6 +11,33 @@ namespace SixLabors.ImageSharp /// internal static class StreamExtensions { +#if NETCOREAPP2_1 + /// + /// Writes data from a stream into the provided buffer. + /// + /// The stream. + /// The buffer. + /// The offset within the buffer to begin writing. + /// The number of bytes to write to the stream. + public static void Write(this Stream stream, Span buffer, int offset, int count) + { + stream.Write(buffer.Slice(offset, count)); + } + + /// + /// Reads data from a stream into the provided buffer. + /// + /// The stream. + /// The buffer.. + /// The offset within the buffer where the bytes are read into. + /// The number of bytes, if available, to read. + /// The actual number of bytes read. + public static int Read(this Stream stream, Span buffer, int offset, int count) + { + return stream.Read(buffer.Slice(offset, count)); + } +#endif + /// /// Skips the number of bytes in the given stream. /// diff --git a/src/ImageSharp/Common/Helpers/ImageMaths.cs b/src/ImageSharp/Common/Helpers/ImageMaths.cs index 8a2ece4be..b4e5c094c 100644 --- a/src/ImageSharp/Common/Helpers/ImageMaths.cs +++ b/src/ImageSharp/Common/Helpers/ImageMaths.cs @@ -153,8 +153,8 @@ namespace SixLabors.ImageSharp { int width = bitmap.Width; int height = bitmap.Height; - var topLeft = default(Point); - var bottomRight = default(Point); + Point topLeft = default; + Point bottomRight = default; Func, int, int, float, bool> delegateFunc; diff --git a/src/ImageSharp/Common/Helpers/TestHelpers.cs b/src/ImageSharp/Common/Helpers/TestHelpers.cs new file mode 100644 index 000000000..14e5835b4 --- /dev/null +++ b/src/ImageSharp/Common/Helpers/TestHelpers.cs @@ -0,0 +1,24 @@ +// Copyright(c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +namespace SixLabors.ImageSharp.Common.Helpers +{ + /// + /// Internal utilities intended to be only used in tests. + /// + internal static class TestHelpers + { + /// + /// This constant is useful to verify the target framework ImageSharp has been built against. + /// Only intended to be used in tests! + /// + internal const string ImageSharpBuiltAgainst = +#if NETSTANDARD1_1 + "netstandard1.1"; +#elif NETCOREAPP2_1 + "netcoreapp2.1"; +#else + "netstandard2.0"; +#endif + } +} \ No newline at end of file diff --git a/src/ImageSharp/Formats/Bmp/BmpDecoderCore.cs b/src/ImageSharp/Formats/Bmp/BmpDecoderCore.cs index dd092e643..20175613e 100644 --- a/src/ImageSharp/Formats/Bmp/BmpDecoderCore.cs +++ b/src/ImageSharp/Formats/Bmp/BmpDecoderCore.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. using System; +using System.Buffers.Binary; using System.IO; using System.Runtime.CompilerServices; using SixLabors.ImageSharp.MetaData; @@ -216,7 +217,7 @@ namespace SixLabors.ImageSharp.Formats.Bmp private void ReadRle8(Buffer2D pixels, byte[] colors, int width, int height, bool inverted) where TPixel : struct, IPixel { - var color = default(TPixel); + TPixel color = default; var rgba = new Rgba32(0, 0, 0, 255); using (Buffer2D buffer = this.memoryAllocator.AllocateClean2D(width, height)) @@ -251,7 +252,11 @@ namespace SixLabors.ImageSharp.Formats.Bmp /// Buffer for uncompressed data. private void UncompressRle8(int w, Span buffer) { +#if NETCOREAPP2_1 + Span cmd = stackalloc byte[2]; +#else byte[] cmd = new byte[2]; +#endif int count = 0; while (count < buffer.Length) @@ -392,7 +397,7 @@ namespace SixLabors.ImageSharp.Formats.Bmp { int padding = CalculatePadding(width, 2); int stride = (width * 2) + padding; - var color = default(TPixel); + TPixel color = default; var rgba = new Rgba32(0, 0, 0, 255); using (IManagedByteBuffer buffer = this.memoryAllocator.AllocateManagedByteBuffer(stride)) @@ -475,12 +480,14 @@ namespace SixLabors.ImageSharp.Formats.Bmp /// private void ReadInfoHeader() { +#if NETCOREAPP2_1 + Span buffer = stackalloc byte[BmpInfoHeader.MaxHeaderSize]; +#else byte[] buffer = new byte[BmpInfoHeader.MaxHeaderSize]; +#endif + this.stream.Read(buffer, 0, BmpInfoHeader.HeaderSizeSize); // read the header size - // read header size - this.stream.Read(buffer, 0, BmpInfoHeader.HeaderSizeSize); - - int headerSize = BitConverter.ToInt32(buffer, 0); + int headerSize = BinaryPrimitives.ReadInt32LittleEndian(buffer); if (headerSize < BmpInfoHeader.CoreSize) { throw new NotSupportedException($"ImageSharp does not support this BMP file. HeaderSize: {headerSize}."); @@ -504,7 +511,7 @@ namespace SixLabors.ImageSharp.Formats.Bmp else if (headerSize >= BmpInfoHeader.Size) { // >= 40 bytes - this.infoHeader = BmpInfoHeader.Parse(buffer.AsSpan(0, 40)); + this.infoHeader = BmpInfoHeader.Parse(buffer); } else { @@ -520,8 +527,11 @@ namespace SixLabors.ImageSharp.Formats.Bmp /// private void ReadFileHeader() { +#if NETCOREAPP2_1 + Span buffer = stackalloc byte[BmpFileHeader.Size]; +#else byte[] buffer = new byte[BmpFileHeader.Size]; - +#endif this.stream.Read(buffer, 0, BmpFileHeader.Size); this.fileHeader = BmpFileHeader.Parse(buffer); diff --git a/src/ImageSharp/Formats/Bmp/BmpEncoderCore.cs b/src/ImageSharp/Formats/Bmp/BmpEncoderCore.cs index 1864737c8..a4e61f910 100644 --- a/src/ImageSharp/Formats/Bmp/BmpEncoderCore.cs +++ b/src/ImageSharp/Formats/Bmp/BmpEncoderCore.cs @@ -66,8 +66,11 @@ namespace SixLabors.ImageSharp.Formats.Bmp reserved: 0, fileSize: 54 + infoHeader.ImageSize); - byte[] buffer = new byte[40]; // TODO: stackalloc - +#if NETCOREAPP2_1 + Span buffer = stackalloc byte[40]; +#else + byte[] buffer = new byte[40]; +#endif fileHeader.WriteTo(buffer); stream.Write(buffer, 0, BmpFileHeader.Size); diff --git a/src/ImageSharp/Formats/Bmp/BmpImageFormatDetector.cs b/src/ImageSharp/Formats/Bmp/BmpImageFormatDetector.cs index 9c9786e0a..bb884019b 100644 --- a/src/ImageSharp/Formats/Bmp/BmpImageFormatDetector.cs +++ b/src/ImageSharp/Formats/Bmp/BmpImageFormatDetector.cs @@ -16,12 +16,7 @@ namespace SixLabors.ImageSharp.Formats.Bmp /// public IImageFormat DetectFormat(ReadOnlySpan header) { - if (this.IsSupportedFileFormat(header)) - { - return ImageFormats.Bmp; - } - - return null; + return this.IsSupportedFileFormat(header) ? ImageFormats.Bmp : null; } private bool IsSupportedFileFormat(ReadOnlySpan header) diff --git a/src/ImageSharp/Formats/Bmp/BmpInfoHeader.cs b/src/ImageSharp/Formats/Bmp/BmpInfoHeader.cs index a70716a85..4dd63a962 100644 --- a/src/ImageSharp/Formats/Bmp/BmpInfoHeader.cs +++ b/src/ImageSharp/Formats/Bmp/BmpInfoHeader.cs @@ -132,6 +132,11 @@ namespace SixLabors.ImageSharp.Formats.Bmp /// public static BmpInfoHeader Parse(ReadOnlySpan data) { + if (data.Length != Size) + { + throw new ArgumentException(nameof(data), $"Must be {Size} bytes. Was {data.Length} bytes."); + } + return MemoryMarshal.Cast(data)[0]; } diff --git a/src/ImageSharp/Formats/Gif/GifDecoder.cs b/src/ImageSharp/Formats/Gif/GifDecoder.cs index c81c51e8b..ac451a355 100644 --- a/src/ImageSharp/Formats/Gif/GifDecoder.cs +++ b/src/ImageSharp/Formats/Gif/GifDecoder.cs @@ -38,7 +38,7 @@ namespace SixLabors.ImageSharp.Formats.Gif /// public IImageInfo Identify(Configuration configuration, Stream stream) { - Guard.NotNull(stream, "stream"); + Guard.NotNull(stream, nameof(stream)); var decoder = new GifDecoderCore(configuration, this); return decoder.Identify(stream); diff --git a/src/ImageSharp/Formats/Gif/LzwDecoder.cs b/src/ImageSharp/Formats/Gif/LzwDecoder.cs index 977870936..35eb43a8a 100644 --- a/src/ImageSharp/Formats/Gif/LzwDecoder.cs +++ b/src/ImageSharp/Formats/Gif/LzwDecoder.cs @@ -112,7 +112,12 @@ namespace SixLabors.ImageSharp.Formats.Gif Unsafe.Add(ref suffixRef, code) = (byte)code; } +#if NETCOREAPP2_1 + Span buffer = stackalloc byte[255]; +#else byte[] buffer = new byte[255]; +#endif + while (xyz < length) { if (top == 0) @@ -221,15 +226,21 @@ namespace SixLabors.ImageSharp.Formats.Gif /// The . /// [MethodImpl(MethodImplOptions.AggressiveInlining)] +#if NETCOREAPP2_1 + private int ReadBlock(Span buffer) +#else private int ReadBlock(byte[] buffer) +#endif { int bufferSize = this.stream.ReadByte(); + if (bufferSize < 1) { return 0; } int count = this.stream.Read(buffer, 0, bufferSize); + return count != bufferSize ? 0 : bufferSize; } diff --git a/src/ImageSharp/Formats/IImageEncoder.cs b/src/ImageSharp/Formats/IImageEncoder.cs index ac0b6e311..76d831d5a 100644 --- a/src/ImageSharp/Formats/IImageEncoder.cs +++ b/src/ImageSharp/Formats/IImageEncoder.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/IImageFormatDetector.cs b/src/ImageSharp/Formats/IImageFormatDetector.cs index 8266439bd..da3730d20 100644 --- a/src/ImageSharp/Formats/IImageFormatDetector.cs +++ b/src/ImageSharp/Formats/IImageFormatDetector.cs @@ -2,8 +2,6 @@ // Licensed under the Apache License, Version 2.0. using System; -using System.Collections.Generic; -using System.Text; namespace SixLabors.ImageSharp.Formats { diff --git a/src/ImageSharp/Formats/ImageFormatManager.cs b/src/ImageSharp/Formats/ImageFormatManager.cs index 4e33a0445..63fd02d8d 100644 --- a/src/ImageSharp/Formats/ImageFormatManager.cs +++ b/src/ImageSharp/Formats/ImageFormatManager.cs @@ -5,7 +5,6 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; -using System.Text; namespace SixLabors.ImageSharp.Formats { @@ -87,9 +86,9 @@ namespace SixLabors.ImageSharp.Formats { Guard.NotNullOrWhiteSpace(extension, nameof(extension)); - if (extension[0] == '.') - { - extension = extension.Substring(1); + if (extension[0] == '.') + { + extension = extension.Substring(1); } return this.imageFormats.FirstOrDefault(x => x.FileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase)); @@ -158,12 +157,10 @@ namespace SixLabors.ImageSharp.Formats public IImageDecoder FindDecoder(IImageFormat format) { Guard.NotNull(format, nameof(format)); - if (this.mimeTypeDecoders.TryGetValue(format, out IImageDecoder decoder)) - { - return decoder; - } - return null; + return this.mimeTypeDecoders.TryGetValue(format, out IImageDecoder decoder) + ? decoder + : null; } /// @@ -174,12 +171,10 @@ namespace SixLabors.ImageSharp.Formats public IImageEncoder FindEncoder(IImageFormat format) { Guard.NotNull(format, nameof(format)); - if (this.mimeTypeEncoders.TryGetValue(format, out IImageEncoder encoder)) - { - return encoder; - } - return null; + return this.mimeTypeEncoders.TryGetValue(format, out IImageEncoder encoder) + ? encoder + : null; } /// diff --git a/src/ImageSharp/Formats/Jpeg/Components/Block8x8.cs b/src/ImageSharp/Formats/Jpeg/Components/Block8x8.cs index cb73ee947..5601a9436 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/Block8x8.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/Block8x8.cs @@ -184,7 +184,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components /// public Block8x8F AsFloatBlock() { - var result = default(Block8x8F); + Block8x8F result = default; result.LoadFrom(ref this); return result; } diff --git a/src/ImageSharp/Formats/Jpeg/Components/Block8x8F.cs b/src/ImageSharp/Formats/Jpeg/Components/Block8x8F.cs index 38974cc76..59fc234c4 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/Block8x8F.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/Block8x8F.cs @@ -134,14 +134,14 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components public static Block8x8F Load(Span data) { - var result = default(Block8x8F); + Block8x8F result = default; result.LoadFrom(data); return result; } public static Block8x8F Load(Span data) { - var result = default(Block8x8F); + Block8x8F result = default; result.LoadFrom(data); return result; } @@ -461,7 +461,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components public Block8x8 RoundAsInt16Block() { - var result = default(Block8x8); + Block8x8 result = default; this.RoundInto(ref result); return result; } diff --git a/src/ImageSharp/Formats/Jpeg/Components/Decoder/ColorConverters/JpegColorConverter.FromYCbCrSimdAvx2.cs b/src/ImageSharp/Formats/Jpeg/Components/Decoder/ColorConverters/JpegColorConverter.FromYCbCrSimdAvx2.cs index c43713bf4..25342f4d6 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/Decoder/ColorConverters/JpegColorConverter.FromYCbCrSimdAvx2.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/Decoder/ColorConverters/JpegColorConverter.FromYCbCrSimdAvx2.cs @@ -62,9 +62,9 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Decoder.ColorConverters // Walking 8 elements at one step: int n = result.Length / 8; - var rr = default(Vector4Pair); - var gg = default(Vector4Pair); - var bb = default(Vector4Pair); + Vector4Pair rr = default; + Vector4Pair gg = default; + Vector4Pair bb = default; ref Vector rrRefAsVector = ref Unsafe.As>(ref rr); ref Vector ggRefAsVector = ref Unsafe.As>(ref gg); diff --git a/src/ImageSharp/Formats/Jpeg/Components/Decoder/ColorConverters/JpegColorConverter.cs b/src/ImageSharp/Formats/Jpeg/Components/Decoder/ColorConverters/JpegColorConverter.cs index 5105e57ab..2937b23a7 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/Decoder/ColorConverters/JpegColorConverter.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/Decoder/ColorConverters/JpegColorConverter.cs @@ -62,7 +62,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Decoder.ColorConverters /// Returns the for the YCbCr colorspace that matches the current CPU architecture. /// private static JpegColorConverter GetYCbCrConverter() => - JpegColorConverter.FromYCbCrSimdAvx2.IsAvailable ? (JpegColorConverter)new JpegColorConverter.FromYCbCrSimdAvx2() : new JpegColorConverter.FromYCbCrSimd(); + FromYCbCrSimdAvx2.IsAvailable ? (JpegColorConverter)new FromYCbCrSimdAvx2() : new FromYCbCrSimd(); /// /// A stack-only struct to reference the input buffers using -s. diff --git a/src/ImageSharp/Formats/Jpeg/Components/Decoder/ProfileResolver.cs b/src/ImageSharp/Formats/Jpeg/Components/Decoder/ProfileResolver.cs index e5de4441c..8273f20ea 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/Decoder/ProfileResolver.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/Decoder/ProfileResolver.cs @@ -37,7 +37,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Decoder /// The bytes to check /// The profile identifier /// The - public static bool IsProfile(Span bytesToCheck, Span profileIdentifier) + public static bool IsProfile(ReadOnlySpan bytesToCheck, ReadOnlySpan profileIdentifier) { return bytesToCheck.Length >= profileIdentifier.Length && bytesToCheck.Slice(0, profileIdentifier.Length).SequenceEqual(profileIdentifier); diff --git a/src/ImageSharp/Formats/Jpeg/GolangPort/Components/Decoder/GolangJpegScanDecoder.ComputationData.cs b/src/ImageSharp/Formats/Jpeg/GolangPort/Components/Decoder/GolangJpegScanDecoder.ComputationData.cs index f1dd2526a..f3c8aa91b 100644 --- a/src/ImageSharp/Formats/Jpeg/GolangPort/Components/Decoder/GolangJpegScanDecoder.ComputationData.cs +++ b/src/ImageSharp/Formats/Jpeg/GolangPort/Components/Decoder/GolangJpegScanDecoder.ComputationData.cs @@ -44,7 +44,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.GolangPort.Components.Decoder /// The public static ComputationData Create() { - var data = default(ComputationData); + ComputationData data = default; data.Unzig = ZigZag.CreateUnzigTable(); return data; } diff --git a/src/ImageSharp/Formats/Jpeg/GolangPort/GolangJpegDecoderCore.cs b/src/ImageSharp/Formats/Jpeg/GolangPort/GolangJpegDecoderCore.cs index 34a6e2f0f..46cdcddb4 100644 --- a/src/ImageSharp/Formats/Jpeg/GolangPort/GolangJpegDecoderCore.cs +++ b/src/ImageSharp/Formats/Jpeg/GolangPort/GolangJpegDecoderCore.cs @@ -338,6 +338,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.GolangPort break; case JpegConstants.Markers.DHT: + if (metadataOnly) { this.InputProcessor.Skip(remaining); @@ -721,7 +722,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.GolangPort { if (remaining < 17) { - throw new ImageFormatException("DHT has wrong length"); + throw new ImageFormatException($"DHT has wrong length. {remaining}"); } this.InputProcessor.ReadFull(this.Temp, 0, 17); @@ -772,7 +773,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.GolangPort /// private void ProcessStartOfScanMarker(int remaining) { - var scan = default(GolangJpegScanDecoder); + GolangJpegScanDecoder scan = default; GolangJpegScanDecoder.InitStreamReading(&scan, this, remaining); this.InputProcessor.Bits = default; scan.DecodeBlocks(this); diff --git a/src/ImageSharp/Formats/Jpeg/JpegDecoder.cs b/src/ImageSharp/Formats/Jpeg/JpegDecoder.cs index e738982cb..eafbb391c 100644 --- a/src/ImageSharp/Formats/Jpeg/JpegDecoder.cs +++ b/src/ImageSharp/Formats/Jpeg/JpegDecoder.cs @@ -33,7 +33,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg /// public IImageInfo Identify(Configuration configuration, Stream stream) { - Guard.NotNull(stream, "stream"); + Guard.NotNull(stream, nameof(stream)); using (var decoder = new PdfJsJpegDecoderCore(configuration, this)) { diff --git a/src/ImageSharp/Formats/Jpeg/JpegEncoderCore.cs b/src/ImageSharp/Formats/Jpeg/JpegEncoderCore.cs index 37279d526..1310d90d2 100644 --- a/src/ImageSharp/Formats/Jpeg/JpegEncoderCore.cs +++ b/src/ImageSharp/Formats/Jpeg/JpegEncoderCore.cs @@ -1,6 +1,7 @@ // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. +using System; using System.IO; using System.Runtime.CompilerServices; @@ -543,15 +544,16 @@ namespace SixLabors.ImageSharp.Formats.Jpeg specs = new[] { HuffmanSpec.TheHuffmanSpecs[0], HuffmanSpec.TheHuffmanSpecs[1] }; } - foreach (HuffmanSpec s in specs) + for (int i = 0; i < specs.Length; i++) { + ref HuffmanSpec s = ref specs[i]; markerlen += 1 + 16 + s.Values.Length; } this.WriteMarkerHeader(JpegConstants.Markers.DHT, markerlen); for (int i = 0; i < specs.Length; i++) { - HuffmanSpec spec = specs[i]; + ref HuffmanSpec spec = ref specs[i]; int len = 0; fixed (byte* huffman = this.huffmanBuffer) @@ -736,16 +738,16 @@ namespace SixLabors.ImageSharp.Formats.Jpeg private void WriteStartOfFrame(int width, int height, int componentCount) { // "default" to 4:2:0 - byte[] subsamples = { 0x22, 0x11, 0x11 }; - byte[] chroma = { 0x00, 0x01, 0x01 }; + Span subsamples = stackalloc byte[] { 0x22, 0x11, 0x11 }; + Span chroma = stackalloc byte[] { 0x00, 0x01, 0x01 }; switch (this.subsample) { case JpegSubsample.Ratio444: - subsamples = new byte[] { 0x11, 0x11, 0x11 }; + subsamples = stackalloc byte[] { 0x11, 0x11, 0x11 }; break; case JpegSubsample.Ratio420: - subsamples = new byte[] { 0x22, 0x11, 0x11 }; + subsamples = stackalloc byte[] { 0x22, 0x11, 0x11 }; break; } diff --git a/src/ImageSharp/Formats/Jpeg/PdfJsPort/PdfJsJpegDecoderCore.cs b/src/ImageSharp/Formats/Jpeg/PdfJsPort/PdfJsJpegDecoderCore.cs index 937439ed0..bd1d84ecc 100644 --- a/src/ImageSharp/Formats/Jpeg/PdfJsPort/PdfJsJpegDecoderCore.cs +++ b/src/ImageSharp/Formats/Jpeg/PdfJsPort/PdfJsJpegDecoderCore.cs @@ -270,6 +270,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.PdfJsPort } case JpegConstants.Markers.DHT: + if (metadataOnly) { this.InputStream.Skip(remaining); @@ -698,11 +699,6 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.PdfJsPort /// The remaining bytes in the segment block. private void ProcessDefineHuffmanTablesMarker(int remaining) { - if (remaining < 17) - { - throw new ImageFormatException($"DHT has wrong length: {remaining}"); - } - using (IManagedByteBuffer huffmanData = this.configuration.MemoryAllocator.AllocateCleanManagedByteBuffer(256)) { ref byte huffmanDataRef = ref MemoryMarshal.GetReference(huffmanData.GetSpan()); @@ -790,7 +786,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.PdfJsPort int spectralStart = this.temp[0]; int spectralEnd = this.temp[1]; int successiveApproximation = this.temp[2]; - var scanDecoder = default(PdfJsScanDecoder); + PdfJsScanDecoder scanDecoder = default; scanDecoder.DecodeScan( this.Frame, diff --git a/src/ImageSharp/Formats/Png/PngDecoderCore.cs b/src/ImageSharp/Formats/Png/PngDecoderCore.cs index dd49e0a80..f7fc54d77 100644 --- a/src/ImageSharp/Formats/Png/PngDecoderCore.cs +++ b/src/ImageSharp/Formats/Png/PngDecoderCore.cs @@ -680,7 +680,7 @@ namespace SixLabors.ImageSharp.Formats.Png private void ProcessDefilteredScanline(ReadOnlySpan defilteredScanline, ImageFrame pixels) where TPixel : struct, IPixel { - var color = default(TPixel); + TPixel color = default; Span rowSpan = pixels.GetPixelRowSpan(this.currentRow); // Trim the first marker byte from the buffer @@ -763,7 +763,7 @@ namespace SixLabors.ImageSharp.Formats.Png for (int x = 0; x < this.header.Width; x++) { ref Rgb24 rgb24 = ref rgb24Span[x]; - var rgba32 = default(Rgba32); + Rgba32 rgba32 = default; rgba32.Rgb = rgb24; rgba32.A = (byte)(rgb24.Equals(this.rgb24Trans) ? 0 : 255); @@ -778,7 +778,7 @@ namespace SixLabors.ImageSharp.Formats.Png for (int x = 0; x < this.header.Width; x++) { ref readonly Rgb24 rgb24 = ref rgb24Span[x]; - var rgba32 = default(Rgba32); + Rgba32 rgba32 = default; rgba32.Rgb = rgb24; rgba32.A = (byte)(rgb24.Equals(this.rgb24Trans) ? 0 : 255); @@ -829,7 +829,7 @@ namespace SixLabors.ImageSharp.Formats.Png /// /// Decodes and assigns marker colors that identify transparent pixels in non indexed images /// - /// The aplha tRNS array + /// The alpha tRNS array private void AssignTransparentMarkers(byte[] alpha) { if (this.pngColorType == PngColorType.Rgb) @@ -858,15 +858,14 @@ namespace SixLabors.ImageSharp.Formats.Png /// /// The type of pixel we are expanding to /// The scanline - /// Thecurrent output image row + /// The current output image row private void ProcessScanlineFromPalette(ReadOnlySpan defilteredScanline, Span row) where TPixel : struct, IPixel { ReadOnlySpan newScanline = ToArrayByBitsLength(defilteredScanline, this.bytesPerScanline, this.header.BitDepth); ReadOnlySpan pal = MemoryMarshal.Cast(this.palette); - var color = default(TPixel); - - var rgba = default(Rgba32); + TPixel color = default; + Rgba32 rgba = default; if (this.paletteAlpha != null && this.paletteAlpha.Length > 0) { @@ -910,7 +909,7 @@ namespace SixLabors.ImageSharp.Formats.Png private void ProcessInterlacedDefilteredScanline(ReadOnlySpan defilteredScanline, Span rowSpan, int pixelOffset = 0, int increment = 1) where TPixel : struct, IPixel { - var color = default(TPixel); + TPixel color = default; // Trim the first marker byte from the buffer ReadOnlySpan scanlineBuffer = defilteredScanline.Slice(1, defilteredScanline.Length - 1); @@ -953,7 +952,7 @@ namespace SixLabors.ImageSharp.Formats.Png case PngColorType.Palette: ReadOnlySpan newScanline = ToArrayByBitsLength(scanlineBuffer, this.bytesPerScanline, this.header.BitDepth); - var rgba = default(Rgba32); + Rgba32 rgba = default; Span pal = MemoryMarshal.Cast(this.palette); if (this.paletteAlpha != null && this.paletteAlpha.Length > 0) diff --git a/src/ImageSharp/Formats/Png/PngEncoderCore.cs b/src/ImageSharp/Formats/Png/PngEncoderCore.cs index 477ca852e..9e0f5f877 100644 --- a/src/ImageSharp/Formats/Png/PngEncoderCore.cs +++ b/src/ImageSharp/Formats/Png/PngEncoderCore.cs @@ -248,7 +248,7 @@ namespace SixLabors.ImageSharp.Formats.Png where TPixel : struct, IPixel { byte[] rawScanlineArray = this.rawScanline.Array; - var rgba = default(Rgba32); + Rgba32 rgba = default; // Copy the pixels across from the image. // Reuse the chunk type buffer. @@ -306,8 +306,9 @@ namespace SixLabors.ImageSharp.Formats.Png switch (this.pngColorType) { case PngColorType.Palette: - // TODO: Use Span copy! - Buffer.BlockCopy(this.palettePixelData, row * this.rawScanline.Length(), this.rawScanline.Array, 0, this.rawScanline.Length()); + int stride = this.rawScanline.Length(); + + this.palettePixelData.AsSpan(row * stride, stride).CopyTo(this.rawScanline.GetSpan()); break; case PngColorType.Grayscale: case PngColorType.GrayscaleWithAlpha: diff --git a/src/ImageSharp/Formats/Png/PngImageFormatDetector.cs b/src/ImageSharp/Formats/Png/PngImageFormatDetector.cs index 36b43a470..c1c039a1b 100644 --- a/src/ImageSharp/Formats/Png/PngImageFormatDetector.cs +++ b/src/ImageSharp/Formats/Png/PngImageFormatDetector.cs @@ -17,12 +17,7 @@ namespace SixLabors.ImageSharp.Formats.Png /// public IImageFormat DetectFormat(ReadOnlySpan header) { - if (this.IsSupportedFileFormat(header)) - { - return ImageFormats.Png; - } - - return null; + return this.IsSupportedFileFormat(header) ? ImageFormats.Png : null; } private bool IsSupportedFileFormat(ReadOnlySpan header) diff --git a/src/ImageSharp/Image.Decode.cs b/src/ImageSharp/Image.Decode.cs index 443ae6a37..9087db414 100644 --- a/src/ImageSharp/Image.Decode.cs +++ b/src/ImageSharp/Image.Decode.cs @@ -48,12 +48,10 @@ namespace SixLabors.ImageSharp private static IImageDecoder DiscoverDecoder(Stream stream, Configuration config, out IImageFormat format) { format = InternalDetectFormat(stream, config); - if (format != null) - { - return config.ImageFormatsManager.FindDecoder(format); - } - return null; + return format != null + ? config.ImageFormatsManager.FindDecoder(format) + : null; } #pragma warning disable SA1008 // Opening parenthesis must be spaced correctly diff --git a/src/ImageSharp/ImageSharp.csproj b/src/ImageSharp/ImageSharp.csproj index 777c5016c..b40884f4b 100644 --- a/src/ImageSharp/ImageSharp.csproj +++ b/src/ImageSharp/ImageSharp.csproj @@ -5,7 +5,7 @@ $(packageversion) 0.0.1 Six Labors and contributors - netstandard1.1;netstandard1.3;netstandard2.0 + netstandard1.1;netstandard1.3;netstandard2.0;netcoreapp2.1 true true SixLabors.ImageSharp @@ -29,7 +29,7 @@ portable True IOperation - 7.2 + 7.3 @@ -40,13 +40,21 @@ All + + + + + + + - - + + + diff --git a/src/ImageSharp/MetaData/ImageFrameMetaData.cs b/src/ImageSharp/MetaData/ImageFrameMetaData.cs index ca3012f4a..d507a5b3e 100644 --- a/src/ImageSharp/MetaData/ImageFrameMetaData.cs +++ b/src/ImageSharp/MetaData/ImageFrameMetaData.cs @@ -1,7 +1,6 @@ // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.Formats.Gif; namespace SixLabors.ImageSharp.MetaData diff --git a/src/ImageSharp/MetaData/Profiles/Exif/ExifConstants.cs b/src/ImageSharp/MetaData/Profiles/Exif/ExifConstants.cs new file mode 100644 index 000000000..a76737b69 --- /dev/null +++ b/src/ImageSharp/MetaData/Profiles/Exif/ExifConstants.cs @@ -0,0 +1,31 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +namespace SixLabors.ImageSharp.MetaData.Profiles.Exif +{ + internal static class ExifConstants + { + public static readonly byte[] ExifIdCode = { + (byte)'E', + (byte)'x', + (byte)'i', + (byte)'f', + 0x00, + 0x00 + }; + + public static readonly byte[] LittleEndianByteOrderMarker = { + (byte)'I', + (byte)'I', + 0x2A, + 0x00, + }; + + public static readonly byte[] BigEndianByteOrderMarker = { + (byte)'M', + (byte)'M', + 0x2A, + 0x00, + }; + } +} \ No newline at end of file diff --git a/src/ImageSharp/MetaData/Profiles/Exif/ExifReader.cs b/src/ImageSharp/MetaData/Profiles/Exif/ExifReader.cs index 755d92939..7339feba1 100644 --- a/src/ImageSharp/MetaData/Profiles/Exif/ExifReader.cs +++ b/src/ImageSharp/MetaData/Profiles/Exif/ExifReader.cs @@ -141,26 +141,25 @@ namespace SixLabors.ImageSharp.MetaData.Profiles.Exif private unsafe string ConvertToString(ReadOnlySpan buffer) { -#if NETSTANDARD1_1 - byte[] bytes = buffer.ToArray(); + Span nullChar = stackalloc byte[1] { 0 }; - string result = Encoding.UTF8.GetString(bytes, 0, buffer.Length); + int nullCharIndex = buffer.IndexOf(nullChar); -#else - string result; + if (nullCharIndex > -1) + { + buffer = buffer.Slice(0, nullCharIndex); + } +#if NETSTANDARD1_1 + return Encoding.UTF8.GetString(buffer.ToArray(), 0, buffer.Length); +#elif NETCOREAPP2_1 + return Encoding.UTF8.GetString(buffer); +#else fixed (byte* pointer = &MemoryMarshal.GetReference(buffer)) { - result = Encoding.UTF8.GetString(pointer, buffer.Length); + return Encoding.UTF8.GetString(pointer, buffer.Length); } #endif - int nullCharIndex = result.IndexOf('\0'); - if (nullCharIndex != -1) - { - result = result.Substring(0, nullCharIndex); - } - - return result; } /// diff --git a/src/ImageSharp/MetaData/Profiles/Exif/ExifWriter.cs b/src/ImageSharp/MetaData/Profiles/Exif/ExifWriter.cs index 914cd4b36..14d180c05 100644 --- a/src/ImageSharp/MetaData/Profiles/Exif/ExifWriter.cs +++ b/src/ImageSharp/MetaData/Profiles/Exif/ExifWriter.cs @@ -106,19 +106,13 @@ namespace SixLabors.ImageSharp.MetaData.Profiles.Exif int i = 0; if (includeExifIdCode) { - result[i++] = (byte)'E'; - result[i++] = (byte)'x'; - result[i++] = (byte)'i'; - result[i++] = (byte)'f'; - result[i++] = 0x00; - result[i++] = 0x00; + ExifConstants.ExifIdCode.AsSpan().CopyTo(result); // 0-5 + i += ExifConstants.ExifIdCode.Length; } // the byte order marker for little-endian, followed by the number 42 and a 0 - result[i++] = (byte)'I'; - result[i++] = (byte)'I'; - result[i++] = 0x2A; - result[i++] = 0x00; + ExifConstants.LittleEndianByteOrderMarker.AsSpan().CopyTo(result.AsSpan(start: i)); + i += ExifConstants.LittleEndianByteOrderMarker.Length; uint ifdOffset = ((uint)i - startIndex) + 4; uint thumbnailOffset = ifdOffset + ifdLength + exifLength + gpsLength; @@ -268,7 +262,7 @@ namespace SixLabors.ImageSharp.MetaData.Profiles.Exif return length; } - private int WriteArray(ExifValue value, byte[] destination, int offset) + private int WriteArray(ExifValue value, Span destination, int offset) { if (value.DataType == ExifDataType.Ascii) { @@ -284,7 +278,7 @@ namespace SixLabors.ImageSharp.MetaData.Profiles.Exif return newOffset; } - private int WriteData(uint startIndex, List indexes, byte[] destination, int offset) + private int WriteData(uint startIndex, List indexes, Span destination, int offset) { if (this.dataOffsets.Count == 0) { @@ -307,7 +301,7 @@ namespace SixLabors.ImageSharp.MetaData.Profiles.Exif return newOffset; } - private int WriteHeaders(List indexes, byte[] destination, int offset) + private int WriteHeaders(List indexes, Span destination, int offset) { this.dataOffsets = new List(); @@ -388,7 +382,7 @@ namespace SixLabors.ImageSharp.MetaData.Profiles.Exif } } - private int WriteValue(ExifValue value, byte[] destination, int offset) + private int WriteValue(ExifValue value, Span destination, int offset) { if (value.IsArray && value.DataType != ExifDataType.Ascii) { diff --git a/src/ImageSharp/PixelFormats/Bgr24.cs b/src/ImageSharp/PixelFormats/Bgr24.cs index b099bab1c..ff913923e 100644 --- a/src/ImageSharp/PixelFormats/Bgr24.cs +++ b/src/ImageSharp/PixelFormats/Bgr24.cs @@ -121,7 +121,7 @@ namespace SixLabors.ImageSharp.PixelFormats [MethodImpl(MethodImplOptions.AggressiveInlining)] public void PackFromVector4(Vector4 vector) { - var rgba = default(Rgba32); + Rgba32 rgba = default; rgba.PackFromVector4(vector); this.PackFromRgba32(rgba); } diff --git a/src/ImageSharp/PixelFormats/PixelBlenders/PorterDuffFunctions.Generated.cs b/src/ImageSharp/PixelFormats/PixelBlenders/PorterDuffFunctions.Generated.cs index e948c05ca..66cc427de 100644 --- a/src/ImageSharp/PixelFormats/PixelBlenders/PorterDuffFunctions.Generated.cs +++ b/src/ImageSharp/PixelFormats/PixelBlenders/PorterDuffFunctions.Generated.cs @@ -261,7 +261,7 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders public static TPixel Normal(TPixel backdrop, TPixel source, float amount) where TPixel : struct, IPixel { - TPixel dest = default(TPixel); + TPixel dest = default; dest.PackFromVector4(Normal(backdrop.ToVector4(), source.ToVector4(), amount)); return dest; } @@ -270,7 +270,7 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders public static TPixel Multiply(TPixel backdrop, TPixel source, float amount) where TPixel : struct, IPixel { - TPixel dest = default(TPixel); + TPixel dest = default; dest.PackFromVector4(Multiply(backdrop.ToVector4(), source.ToVector4(), amount)); return dest; } @@ -279,7 +279,7 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders public static TPixel Add(TPixel backdrop, TPixel source, float amount) where TPixel : struct, IPixel { - TPixel dest = default(TPixel); + TPixel dest = default; dest.PackFromVector4(Add(backdrop.ToVector4(), source.ToVector4(), amount)); return dest; } @@ -288,7 +288,7 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders public static TPixel Subtract(TPixel backdrop, TPixel source, float amount) where TPixel : struct, IPixel { - TPixel dest = default(TPixel); + TPixel dest = default; dest.PackFromVector4(Subtract(backdrop.ToVector4(), source.ToVector4(), amount)); return dest; } @@ -297,7 +297,7 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders public static TPixel Screen(TPixel backdrop, TPixel source, float amount) where TPixel : struct, IPixel { - TPixel dest = default(TPixel); + TPixel dest = default; dest.PackFromVector4(Screen(backdrop.ToVector4(), source.ToVector4(), amount)); return dest; } @@ -306,7 +306,7 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders public static TPixel Darken(TPixel backdrop, TPixel source, float amount) where TPixel : struct, IPixel { - TPixel dest = default(TPixel); + TPixel dest = default; dest.PackFromVector4(Darken(backdrop.ToVector4(), source.ToVector4(), amount)); return dest; } @@ -315,7 +315,7 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders public static TPixel Lighten(TPixel backdrop, TPixel source, float amount) where TPixel : struct, IPixel { - TPixel dest = default(TPixel); + TPixel dest = default; dest.PackFromVector4(Lighten(backdrop.ToVector4(), source.ToVector4(), amount)); return dest; } @@ -324,7 +324,7 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders public static TPixel Overlay(TPixel backdrop, TPixel source, float amount) where TPixel : struct, IPixel { - TPixel dest = default(TPixel); + TPixel dest = default; dest.PackFromVector4(Overlay(backdrop.ToVector4(), source.ToVector4(), amount)); return dest; } @@ -333,7 +333,7 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders public static TPixel HardLight(TPixel backdrop, TPixel source, float amount) where TPixel : struct, IPixel { - TPixel dest = default(TPixel); + TPixel dest = default; dest.PackFromVector4(HardLight(backdrop.ToVector4(), source.ToVector4(), amount)); return dest; } @@ -342,7 +342,7 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders public static TPixel Src(TPixel backdrop, TPixel source, float amount) where TPixel : struct, IPixel { - TPixel dest = default(TPixel); + TPixel dest = default; dest.PackFromVector4(Src(backdrop.ToVector4(), source.ToVector4(), amount)); return dest; } @@ -351,7 +351,7 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders public static TPixel Atop(TPixel backdrop, TPixel source, float amount) where TPixel : struct, IPixel { - TPixel dest = default(TPixel); + TPixel dest = default; dest.PackFromVector4(Atop(backdrop.ToVector4(), source.ToVector4(), amount)); return dest; } @@ -360,7 +360,7 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders public static TPixel Over(TPixel backdrop, TPixel source, float amount) where TPixel : struct, IPixel { - TPixel dest = default(TPixel); + TPixel dest = default; dest.PackFromVector4(Over(backdrop.ToVector4(), source.ToVector4(), amount)); return dest; } @@ -369,7 +369,7 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders public static TPixel In(TPixel backdrop, TPixel source, float amount) where TPixel : struct, IPixel { - TPixel dest = default(TPixel); + TPixel dest = default; dest.PackFromVector4(In(backdrop.ToVector4(), source.ToVector4(), amount)); return dest; } @@ -378,7 +378,7 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders public static TPixel Out(TPixel backdrop, TPixel source, float amount) where TPixel : struct, IPixel { - TPixel dest = default(TPixel); + TPixel dest = default; dest.PackFromVector4(Out(backdrop.ToVector4(), source.ToVector4(), amount)); return dest; } @@ -387,7 +387,7 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders public static TPixel Dest(TPixel backdrop, TPixel source, float amount) where TPixel : struct, IPixel { - TPixel dest = default(TPixel); + TPixel dest = default; dest.PackFromVector4(Dest(backdrop.ToVector4(), source.ToVector4(), amount)); return dest; } @@ -396,7 +396,7 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders public static TPixel DestAtop(TPixel backdrop, TPixel source, float amount) where TPixel : struct, IPixel { - TPixel dest = default(TPixel); + TPixel dest = default; dest.PackFromVector4(DestAtop(backdrop.ToVector4(), source.ToVector4(), amount)); return dest; } @@ -405,7 +405,7 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders public static TPixel DestOver(TPixel backdrop, TPixel source, float amount) where TPixel : struct, IPixel { - TPixel dest = default(TPixel); + TPixel dest = default; dest.PackFromVector4(DestOver(backdrop.ToVector4(), source.ToVector4(), amount)); return dest; } @@ -414,7 +414,7 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders public static TPixel DestIn(TPixel backdrop, TPixel source, float amount) where TPixel : struct, IPixel { - TPixel dest = default(TPixel); + TPixel dest = default; dest.PackFromVector4(DestIn(backdrop.ToVector4(), source.ToVector4(), amount)); return dest; } @@ -423,7 +423,7 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders public static TPixel DestOut(TPixel backdrop, TPixel source, float amount) where TPixel : struct, IPixel { - TPixel dest = default(TPixel); + TPixel dest = default; dest.PackFromVector4(DestOut(backdrop.ToVector4(), source.ToVector4(), amount)); return dest; } @@ -432,7 +432,7 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders public static TPixel Clear(TPixel backdrop, TPixel source, float amount) where TPixel : struct, IPixel { - TPixel dest = default(TPixel); + TPixel dest = default; dest.PackFromVector4(Clear(backdrop.ToVector4(), source.ToVector4(), amount)); return dest; } @@ -441,7 +441,7 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders public static TPixel Xor(TPixel backdrop, TPixel source, float amount) where TPixel : struct, IPixel { - TPixel dest = default(TPixel); + TPixel dest = default; dest.PackFromVector4(Xor(backdrop.ToVector4(), source.ToVector4(), amount)); return dest; } diff --git a/src/ImageSharp/PixelFormats/PixelBlenders/PorterDuffFunctions.Generated.tt b/src/ImageSharp/PixelFormats/PixelBlenders/PorterDuffFunctions.Generated.tt index 940b585aa..4cbc06861 100644 --- a/src/ImageSharp/PixelFormats/PixelBlenders/PorterDuffFunctions.Generated.tt +++ b/src/ImageSharp/PixelFormats/PixelBlenders/PorterDuffFunctions.Generated.tt @@ -30,7 +30,7 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders public static TPixel <#=blender#>(TPixel backdrop, TPixel source, float amount) where TPixel : struct, IPixel { - TPixel dest = default(TPixel); + TPixel dest = default; dest.PackFromVector4(<#=blender#>(backdrop.ToVector4(), source.ToVector4(), amount)); return dest; } diff --git a/src/ImageSharp/PixelFormats/Rgb24.cs b/src/ImageSharp/PixelFormats/Rgb24.cs index c540a7d12..faee3bbbd 100644 --- a/src/ImageSharp/PixelFormats/Rgb24.cs +++ b/src/ImageSharp/PixelFormats/Rgb24.cs @@ -122,7 +122,7 @@ namespace SixLabors.ImageSharp.PixelFormats [MethodImpl(MethodImplOptions.AggressiveInlining)] public void PackFromVector4(Vector4 vector) { - var rgba = default(Rgba32); + Rgba32 rgba = default; rgba.PackFromVector4(vector); this.PackFromRgba32(rgba); } diff --git a/src/ImageSharp/PixelFormats/Rgba1010102.cs b/src/ImageSharp/PixelFormats/Rgba1010102.cs index 166936d5e..ee4865e4e 100644 --- a/src/ImageSharp/PixelFormats/Rgba1010102.cs +++ b/src/ImageSharp/PixelFormats/Rgba1010102.cs @@ -188,7 +188,7 @@ namespace SixLabors.ImageSharp.PixelFormats /// public override bool Equals(object obj) { - return (obj is Rgba1010102) && this.Equals((Rgba1010102)obj); + return obj is Rgba1010102 other && this.Equals(other); } /// diff --git a/src/ImageSharp/PixelFormats/Rgba32.cs b/src/ImageSharp/PixelFormats/Rgba32.cs index f6979aad8..bd014a58f 100644 --- a/src/ImageSharp/PixelFormats/Rgba32.cs +++ b/src/ImageSharp/PixelFormats/Rgba32.cs @@ -387,7 +387,7 @@ namespace SixLabors.ImageSharp.PixelFormats /// public override bool Equals(object obj) { - return (obj is Rgba32) && this.Equals((Rgba32)obj); + return obj is Rgba32 other && this.Equals(other); } /// diff --git a/src/ImageSharp/PixelFormats/Rgba64.cs b/src/ImageSharp/PixelFormats/Rgba64.cs index 5d1aa0067..6b891a7c0 100644 --- a/src/ImageSharp/PixelFormats/Rgba64.cs +++ b/src/ImageSharp/PixelFormats/Rgba64.cs @@ -187,7 +187,7 @@ namespace SixLabors.ImageSharp.PixelFormats /// public override bool Equals(object obj) { - return (obj is Rgba64) && this.Equals((Rgba64)obj); + return obj is Rgba64 other && this.Equals(other); } /// diff --git a/src/ImageSharp/Primitives/DenseMatrix{T}.cs b/src/ImageSharp/Primitives/DenseMatrix{T}.cs index 5f3defd11..ef1abc897 100644 --- a/src/ImageSharp/Primitives/DenseMatrix{T}.cs +++ b/src/ImageSharp/Primitives/DenseMatrix{T}.cs @@ -89,6 +89,11 @@ namespace SixLabors.ImageSharp.Primitives } } + /// + /// Gets a Span wrapping the Data. + /// + internal Span Span => new Span(this.Data); + /// /// Gets or sets the item at the specified position. /// @@ -146,19 +151,13 @@ namespace SixLabors.ImageSharp.Primitives /// /// The value to fill each item with [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Fill(T value) - { - for (int i = 0; i < this.Data.Length; i++) - { - this.Data[i] = value; - } - } + public void Fill(T value) => this.Span.Fill(value); /// /// Clears the matrix setting each value to the default value for the element type /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Clear() => Array.Clear(this.Data, 0, this.Data.Length); + public void Clear() => this.Span.Clear(); /// /// Checks the coordinates to ensure they are within bounds. @@ -183,28 +182,10 @@ namespace SixLabors.ImageSharp.Primitives } /// - public bool Equals(DenseMatrix other) - { - if (this.Columns != other.Columns) - { - return false; - } - - if (this.Rows != other.Rows) - { - return false; - } - - for (int i = 0; i < this.Data.Length; i++) - { - if (!this.Data[i].Equals(other.Data[i])) - { - return false; - } - } - - return true; - } + public bool Equals(DenseMatrix other) => + this.Columns == other.Columns && + this.Rows == other.Rows && + this.Span.SequenceEqual(other.Span); /// public override bool Equals(object obj) => obj is DenseMatrix other && this.Equals(other); diff --git a/src/ImageSharp/Processing/Binarization/Processors/BinaryErrorDiffusionProcessor.cs b/src/ImageSharp/Processing/Binarization/Processors/BinaryErrorDiffusionProcessor.cs index 6588bbe5b..64763b657 100644 --- a/src/ImageSharp/Processing/Binarization/Processors/BinaryErrorDiffusionProcessor.cs +++ b/src/ImageSharp/Processing/Binarization/Processors/BinaryErrorDiffusionProcessor.cs @@ -78,7 +78,7 @@ namespace SixLabors.ImageSharp.Processing.Binarization.Processors protected override void OnFrameApply(ImageFrame source, Rectangle sourceRectangle, Configuration configuration) { float threshold = this.Threshold * 255F; - var rgba = default(Rgba32); + Rgba32 rgba = default; bool isAlphaOnly = typeof(TPixel) == typeof(Alpha8); var interest = Rectangle.Intersect(sourceRectangle, source.Bounds()); diff --git a/src/ImageSharp/Processing/Binarization/Processors/BinaryOrderedDitherProcessor.cs b/src/ImageSharp/Processing/Binarization/Processors/BinaryOrderedDitherProcessor.cs index bd4b3660a..3fe56ff44 100644 --- a/src/ImageSharp/Processing/Binarization/Processors/BinaryOrderedDitherProcessor.cs +++ b/src/ImageSharp/Processing/Binarization/Processors/BinaryOrderedDitherProcessor.cs @@ -59,7 +59,7 @@ namespace SixLabors.ImageSharp.Processing.Binarization.Processors /// protected override void OnFrameApply(ImageFrame source, Rectangle sourceRectangle, Configuration configuration) { - var rgba = default(Rgba32); + Rgba32 rgba = default; bool isAlphaOnly = typeof(TPixel) == typeof(Alpha8); var interest = Rectangle.Intersect(sourceRectangle, source.Bounds()); diff --git a/src/ImageSharp/Processing/Binarization/Processors/BinaryThresholdProcessor.cs b/src/ImageSharp/Processing/Binarization/Processors/BinaryThresholdProcessor.cs index 455c6ad8c..dc1297d6f 100644 --- a/src/ImageSharp/Processing/Binarization/Processors/BinaryThresholdProcessor.cs +++ b/src/ImageSharp/Processing/Binarization/Processors/BinaryThresholdProcessor.cs @@ -77,7 +77,7 @@ namespace SixLabors.ImageSharp.Processing.Binarization.Processors y => { Span row = source.GetPixelRowSpan(y); - var rgba = default(Rgba32); + Rgba32 rgba = default; for (int x = startX; x < endX; x++) { diff --git a/src/ImageSharp/Processing/Convolution/Processors/Convolution2PassProcessor.cs b/src/ImageSharp/Processing/Convolution/Processors/Convolution2PassProcessor.cs index a080beb88..4e14882ff 100644 --- a/src/ImageSharp/Processing/Convolution/Processors/Convolution2PassProcessor.cs +++ b/src/ImageSharp/Processing/Convolution/Processors/Convolution2PassProcessor.cs @@ -92,7 +92,7 @@ namespace SixLabors.ImageSharp.Processing.Convolution.Processors for (int x = startX; x < endX; x++) { - var destination = default(Vector4); + Vector4 destination = default; // Apply each matrix multiplier to the color components for each pixel. for (int fy = 0; fy < kernelHeight; fy++) diff --git a/src/ImageSharp/Processing/Dithering/Processors/ErrorDiffusionPaletteProcessor.cs b/src/ImageSharp/Processing/Dithering/Processors/ErrorDiffusionPaletteProcessor.cs index c90e91a6b..0f9e2d397 100644 --- a/src/ImageSharp/Processing/Dithering/Processors/ErrorDiffusionPaletteProcessor.cs +++ b/src/ImageSharp/Processing/Dithering/Processors/ErrorDiffusionPaletteProcessor.cs @@ -66,7 +66,7 @@ namespace SixLabors.ImageSharp.Processing.Dithering.Processors protected override void OnFrameApply(ImageFrame source, Rectangle sourceRectangle, Configuration configuration) { float threshold = this.Threshold * 255F; - var rgba = default(Rgba32); + Rgba32 rgba = default; bool isAlphaOnly = typeof(TPixel) == typeof(Alpha8); var interest = Rectangle.Intersect(sourceRectangle, source.Bounds()); diff --git a/src/ImageSharp/Processing/Dithering/Processors/OrderedDitherPaletteProcessor.cs b/src/ImageSharp/Processing/Dithering/Processors/OrderedDitherPaletteProcessor.cs index ce9b7fb3e..a59826e23 100644 --- a/src/ImageSharp/Processing/Dithering/Processors/OrderedDitherPaletteProcessor.cs +++ b/src/ImageSharp/Processing/Dithering/Processors/OrderedDitherPaletteProcessor.cs @@ -47,7 +47,7 @@ namespace SixLabors.ImageSharp.Processing.Dithering.Processors /// protected override void OnFrameApply(ImageFrame source, Rectangle sourceRectangle, Configuration configuration) { - var rgba = default(Rgba32); + Rgba32 rgba = default; bool isAlphaOnly = typeof(TPixel) == typeof(Alpha8); var interest = Rectangle.Intersect(sourceRectangle, source.Bounds()); diff --git a/src/ImageSharp/Processing/Dithering/Processors/PaletteDitherProcessorBase.cs b/src/ImageSharp/Processing/Dithering/Processors/PaletteDitherProcessorBase.cs index 89cc7cfb6..683ef7044 100644 --- a/src/ImageSharp/Processing/Dithering/Processors/PaletteDitherProcessorBase.cs +++ b/src/ImageSharp/Processing/Dithering/Processors/PaletteDitherProcessorBase.cs @@ -46,8 +46,8 @@ namespace SixLabors.ImageSharp.Processing.Dithering.Processors float secondLeastDistance = int.MaxValue; var vector = pixel.ToVector4(); - var closest = default(TPixel); - var secondClosest = default(TPixel); + TPixel closest = default; + TPixel secondClosest = default; for (int index = 0; index < colorPalette.Length; index++) { TPixel temp = colorPalette[index]; diff --git a/src/ImageSharp/Processing/Quantization/FrameQuantizers/OctreeFrameQuantizer{TPixel}.cs b/src/ImageSharp/Processing/Quantization/FrameQuantizers/OctreeFrameQuantizer{TPixel}.cs index 431064f22..e32022254 100644 --- a/src/ImageSharp/Processing/Quantization/FrameQuantizers/OctreeFrameQuantizer{TPixel}.cs +++ b/src/ImageSharp/Processing/Quantization/FrameQuantizers/OctreeFrameQuantizer{TPixel}.cs @@ -68,7 +68,7 @@ namespace SixLabors.ImageSharp.Processing.Quantization.FrameQuantizers ref TPixel scanBaseRef = ref MemoryMarshal.GetReference(row); // And loop through each column - var rgba = default(Rgba32); + Rgba32 rgba = default; for (int x = 0; x < width; x++) { ref TPixel pixel = ref Unsafe.Add(ref scanBaseRef, x); @@ -87,7 +87,7 @@ namespace SixLabors.ImageSharp.Processing.Quantization.FrameQuantizers // pass of the algorithm by avoiding transforming rows of identical color. TPixel sourcePixel = source[0, 0]; TPixel previousPixel = sourcePixel; - var rgba = default(Rgba32); + Rgba32 rgba = default; byte pixelValue = this.QuantizePixel(sourcePixel, ref rgba); TPixel[] colorPalette = this.GetPalette(); TPixel transformedPixel = colorPalette[pixelValue]; @@ -152,7 +152,7 @@ namespace SixLabors.ImageSharp.Processing.Quantization.FrameQuantizers { // Transparent pixels are much more likely to be found at the end of a palette int index = this.colors; - var trans = default(Rgba32); + Rgba32 trans = default; for (int i = this.palette.Length - 1; i >= 0; i--) { this.palette[i].ToRgba32(ref trans); @@ -539,7 +539,7 @@ namespace SixLabors.ImageSharp.Processing.Quantization.FrameQuantizers byte b = (this.blue / this.pixelCount).ToByte(); // And set the color of the palette entry - var pixel = default(TPixel); + TPixel pixel = default; pixel.PackFromRgba32(new Rgba32(r, g, b, 255)); palette[index] = pixel; diff --git a/src/ImageSharp/Processing/Quantization/FrameQuantizers/WuFrameQuantizer{TPixel}.cs b/src/ImageSharp/Processing/Quantization/FrameQuantizers/WuFrameQuantizer{TPixel}.cs index 4887519e3..78c4bfbf8 100644 --- a/src/ImageSharp/Processing/Quantization/FrameQuantizers/WuFrameQuantizer{TPixel}.cs +++ b/src/ImageSharp/Processing/Quantization/FrameQuantizers/WuFrameQuantizer{TPixel}.cs @@ -237,7 +237,7 @@ namespace SixLabors.ImageSharp.Processing.Quantization.FrameQuantizers ref TPixel scanBaseRef = ref MemoryMarshal.GetReference(row); // And loop through each column - var rgba = default(Rgba32); + Rgba32 rgba = default; for (int x = 0; x < width; x++) { ref TPixel pixel = ref Unsafe.Add(ref scanBaseRef, x); @@ -858,7 +858,7 @@ namespace SixLabors.ImageSharp.Processing.Quantization.FrameQuantizers } // Expected order r->g->b->a - var rgba = default(Rgba32); + Rgba32 rgba = default; pixel.ToRgba32(ref rgba); int r = rgba.R >> (8 - IndexBits); diff --git a/src/ImageSharp/Processing/Transforms/TransformHelpers.cs b/src/ImageSharp/Processing/Transforms/TransformHelpers.cs index 46dd134ce..71d3b35c1 100644 --- a/src/ImageSharp/Processing/Transforms/TransformHelpers.cs +++ b/src/ImageSharp/Processing/Transforms/TransformHelpers.cs @@ -12,7 +12,7 @@ namespace SixLabors.ImageSharp.Processing.Transforms /// /// Contains helper methods for working with affine and non-affine transforms /// - internal class TransformHelpers + internal static class TransformHelpers { /// /// Updates the dimensional metadata of a transformed image diff --git a/tests/ImageSharp.Benchmarks/Drawing/DrawText.cs b/tests/ImageSharp.Benchmarks/Drawing/DrawText.cs new file mode 100644 index 000000000..96912a6df --- /dev/null +++ b/tests/ImageSharp.Benchmarks/Drawing/DrawText.cs @@ -0,0 +1,101 @@ +// +// Copyright (c) James Jackson-South and contributors. +// Licensed under the Apache License, Version 2.0. +// + +using System.Drawing; +using System.Drawing.Drawing2D; +using BenchmarkDotNet.Attributes; +using System.IO; +using System.Numerics; + +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Processing; +using SixLabors.ImageSharp.Processing.Text; +using SixLabors.ImageSharp.Processing.Overlays; +using SixLabors.ImageSharp.Processing.Drawing; +using System.Linq; + +namespace SixLabors.ImageSharp.Benchmarks +{ + + [MemoryDiagnoser] + public class DrawText : BenchmarkBase + { + + [Params(10, 100)] + public int TextIterations{ get; set; } + public string TextPhrase { get; set; } = "Hello World"; + public string TextToRender => string.Join(" ", Enumerable.Repeat(TextPhrase, TextIterations)); + + + [Benchmark(Baseline = true, Description = "System.Drawing Draw Text")] + public void DrawTextSystemDrawing() + { + using (Bitmap destination = new Bitmap(800, 800)) + { + + using (Graphics graphics = Graphics.FromImage(destination)) + { + graphics.InterpolationMode = InterpolationMode.Default; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + Pen pen = new Pen(System.Drawing.Color.HotPink, 10); + var font = new Font("Arial", 12, GraphicsUnit.Point); + graphics.DrawString(TextToRender, font, Brushes.HotPink, new RectangleF(10, 10, 780, 780)); + } + } + } + + + [Benchmark(Description = "ImageSharp Draw Text - Cached Glyphs")] + public void DrawTextCore() + { + using (Image image = new Image(800, 800)) + { + var font = SixLabors.Fonts.SystemFonts.CreateFont("Arial", 12); + image.Mutate(x => x.ApplyProcessor(new SixLabors.ImageSharp.Processing.Text.Processors.DrawTextProcessor(new TextGraphicsOptions(true) { WrapTextWidth = 780 }, TextToRender, font, SixLabors.ImageSharp.Processing.Drawing.Brushes.Brushes.Solid(Rgba32.HotPink), null, new SixLabors.Primitives.PointF(10, 10)))); + } + } + + [Benchmark(Description = "ImageSharp Draw Text - Nieve")] + public void DrawTextCoreOld() + { + using (Image image = new Image(800, 800)) + { + var font = SixLabors.Fonts.SystemFonts.CreateFont("Arial", 12); + image.Mutate(x => DrawTextOldVersion(x, new TextGraphicsOptions(true) { WrapTextWidth = 780 }, TextToRender, font, SixLabors.ImageSharp.Processing.Drawing.Brushes.Brushes.Solid(Rgba32.HotPink), null, new SixLabors.Primitives.PointF(10, 10))); + } + + IImageProcessingContext DrawTextOldVersion(IImageProcessingContext source, TextGraphicsOptions options, string text, SixLabors.Fonts.Font font, SixLabors.ImageSharp.Processing.Drawing.Brushes.IBrush brush, SixLabors.ImageSharp.Processing.Drawing.Pens.IPen pen, SixLabors.Primitives.PointF location) + where TPixel : struct, IPixel + { + float dpiX = 72; + float dpiY = 72; + + var style = new SixLabors.Fonts.RendererOptions(font, dpiX, dpiY, location) + { + ApplyKerning = options.ApplyKerning, + TabWidth = options.TabWidth, + WrappingWidth = options.WrapTextWidth, + HorizontalAlignment = options.HorizontalAlignment, + VerticalAlignment = options.VerticalAlignment + }; + + Shapes.IPathCollection glyphs = Shapes.TextBuilder.GenerateGlyphs(text, style); + + var pathOptions = (GraphicsOptions)options; + if (brush != null) + { + source.Fill(pathOptions, brush, glyphs); + } + + if (pen != null) + { + source.Draw(pathOptions, pen, glyphs); + } + + return source; + } + } + } +} \ No newline at end of file diff --git a/tests/ImageSharp.Benchmarks/Drawing/DrawTextOutline.cs b/tests/ImageSharp.Benchmarks/Drawing/DrawTextOutline.cs new file mode 100644 index 000000000..e85e33235 --- /dev/null +++ b/tests/ImageSharp.Benchmarks/Drawing/DrawTextOutline.cs @@ -0,0 +1,99 @@ +// +// Copyright (c) James Jackson-South and contributors. +// Licensed under the Apache License, Version 2.0. +// + +using System.Drawing; +using System.Drawing.Drawing2D; +using BenchmarkDotNet.Attributes; +using System.IO; +using System.Numerics; + +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Processing; +using SixLabors.ImageSharp.Processing.Text; +using SixLabors.ImageSharp.Processing.Overlays; +using SixLabors.ImageSharp.Processing.Drawing; +using System.Linq; + +namespace SixLabors.ImageSharp.Benchmarks +{ + + [MemoryDiagnoser] + public class DrawTextOutline : BenchmarkBase + { + + [Params(10, 100)] + public int TextIterations{ get; set; } + public string TextPhrase { get; set; } = "Hello World"; + public string TextToRender => string.Join(" ", Enumerable.Repeat(TextPhrase, TextIterations)); + + + [Benchmark(Baseline = true, Description = "System.Drawing Draw Text Outline")] + public void DrawTextSystemDrawing() + { + using (Bitmap destination = new Bitmap(800, 800)) + { + + using (Graphics graphics = Graphics.FromImage(destination)) + { + graphics.InterpolationMode = InterpolationMode.Default; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + Pen pen = new Pen(System.Drawing.Color.HotPink, 10); + var font = new Font("Arial", 12, GraphicsUnit.Point); + var gp = new GraphicsPath(); + gp.AddString(TextToRender, font.FontFamily, (int)font.Style, font.Size, new RectangleF(10, 10, 780, 780), new StringFormat()); + graphics.DrawPath(pen, gp); + } + } + } + + [Benchmark(Description = "ImageSharp Draw Text Outline - Cached Glyphs")] + public void DrawTextCore() + { + using (Image image = new Image(800, 800)) + { + var font = SixLabors.Fonts.SystemFonts.CreateFont("Arial", 12); + image.Mutate(x => x.ApplyProcessor(new SixLabors.ImageSharp.Processing.Text.Processors.DrawTextProcessor(new TextGraphicsOptions(true) { WrapTextWidth = 780 }, TextToRender, font, null, SixLabors.ImageSharp.Processing.Drawing.Pens.Pens.Solid(Rgba32.HotPink, 10), new SixLabors.Primitives.PointF(10, 10)))); + } + } + + [Benchmark(Description = "ImageSharp Draw Text Outline - Nieve")] + public void DrawTextCoreOld() + { + using (Image image = new Image(800, 800)) + { + var font = SixLabors.Fonts.SystemFonts.CreateFont("Arial", 12); + image.Mutate(x => DrawTextOldVersion(x, new TextGraphicsOptions(true) { WrapTextWidth = 780 }, TextToRender, font, null, SixLabors.ImageSharp.Processing.Drawing.Pens.Pens.Solid(Rgba32.HotPink, 10), new SixLabors.Primitives.PointF(10, 10))); + } + + IImageProcessingContext DrawTextOldVersion(IImageProcessingContext source, TextGraphicsOptions options, string text, SixLabors.Fonts.Font font, SixLabors.ImageSharp.Processing.Drawing.Brushes.IBrush brush, SixLabors.ImageSharp.Processing.Drawing.Pens.IPen pen, SixLabors.Primitives.PointF location) + where TPixel : struct, IPixel + { + var style = new SixLabors.Fonts.RendererOptions(font, options.DpiX, options.DpiY, location) + { + ApplyKerning = options.ApplyKerning, + TabWidth = options.TabWidth, + WrappingWidth = options.WrapTextWidth, + HorizontalAlignment = options.HorizontalAlignment, + VerticalAlignment = options.VerticalAlignment + }; + + Shapes.IPathCollection glyphs = Shapes.TextBuilder.GenerateGlyphs(text, style); + + var pathOptions = (GraphicsOptions)options; + if (brush != null) + { + source.Fill(pathOptions, brush, glyphs); + } + + if (pen != null) + { + source.Draw(pathOptions, pen, glyphs); + } + + return source; + } + } + } +} \ No newline at end of file diff --git a/tests/ImageSharp.Benchmarks/ImageSharp.Benchmarks.csproj b/tests/ImageSharp.Benchmarks/ImageSharp.Benchmarks.csproj index 9a58f350a..67faa7213 100644 --- a/tests/ImageSharp.Benchmarks/ImageSharp.Benchmarks.csproj +++ b/tests/ImageSharp.Benchmarks/ImageSharp.Benchmarks.csproj @@ -18,6 +18,7 @@ + diff --git a/tests/ImageSharp.Sandbox46/ImageSharp.Sandbox46.csproj b/tests/ImageSharp.Sandbox46/ImageSharp.Sandbox46.csproj index 245af5289..3eb5e1247 100644 --- a/tests/ImageSharp.Sandbox46/ImageSharp.Sandbox46.csproj +++ b/tests/ImageSharp.Sandbox46/ImageSharp.Sandbox46.csproj @@ -20,9 +20,9 @@ - - - + + + diff --git a/tests/ImageSharp.Tests/Drawing/BeziersTests.cs b/tests/ImageSharp.Tests/Drawing/BeziersTests.cs index 6dc2fae89..a5fda7958 100644 --- a/tests/ImageSharp.Tests/Drawing/BeziersTests.cs +++ b/tests/ImageSharp.Tests/Drawing/BeziersTests.cs @@ -7,12 +7,11 @@ using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; using SixLabors.ImageSharp.Processing.Drawing; using SixLabors.ImageSharp.Processing.Overlays; +using SixLabors.Memory; using Xunit; namespace SixLabors.ImageSharp.Tests.Drawing { - using SixLabors.Memory; - public class Beziers : FileTestBase { [Fact] diff --git a/tests/ImageSharp.Tests/Drawing/Paths/DrawPathCollection.cs b/tests/ImageSharp.Tests/Drawing/Paths/DrawPathCollection.cs new file mode 100644 index 000000000..ecdfd03e5 --- /dev/null +++ b/tests/ImageSharp.Tests/Drawing/Paths/DrawPathCollection.cs @@ -0,0 +1,117 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System.Numerics; +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Primitives; +using SixLabors.ImageSharp.Processing.Drawing; +using SixLabors.ImageSharp.Processing.Drawing.Brushes; +using SixLabors.ImageSharp.Processing.Drawing.Pens; +using SixLabors.ImageSharp.Processing.Drawing.Processors; +using SixLabors.Shapes; +using Xunit; + +namespace SixLabors.ImageSharp.Tests.Drawing.Paths +{ + public class DrawPathCollection : BaseImageOperationsExtensionTest + { + GraphicsOptions noneDefault = new GraphicsOptions(); + Rgba32 color = Rgba32.HotPink; + Pen pen = Pens.Solid(Rgba32.HotPink, 1); + IPath path1 = new Path(new LinearLineSegment(new SixLabors.Primitives.PointF[] { + new Vector2(10,10), + new Vector2(20,10), + new Vector2(20,10), + new Vector2(30,10), + })); + IPath path2 = new Path(new LinearLineSegment(new SixLabors.Primitives.PointF[] { + new Vector2(10,10), + new Vector2(20,10), + new Vector2(20,10), + new Vector2(30,10), + })); + + IPathCollection pathCollection; + + public DrawPathCollection() + { + this.pathCollection = new PathCollection(this.path1, this.path2); + } + + [Fact] + public void CorrectlySetsBrushAndPath() + { + this.operations.Draw(this.pen, this.pathCollection); + + for (int i = 0; i < 2; i++) + { + FillRegionProcessor processor = this.Verify>(i); + + Assert.Equal(GraphicsOptions.Default, processor.Options); + + ShapePath region = Assert.IsType(processor.Region); + + // path is converted to a polygon before filling + ComplexPolygon polygon = Assert.IsType(region.Shape); + + Assert.Equal(this.pen.StrokeFill, processor.Brush); + } + } + + [Fact] + public void CorrectlySetsBrushPathOptions() + { + this.operations.Draw(this.noneDefault, this.pen, this.pathCollection); + + for (int i = 0; i < 2; i++) + { + FillRegionProcessor processor = this.Verify>(i); + + Assert.Equal(this.noneDefault, processor.Options); + + ShapePath region = Assert.IsType(processor.Region); + ComplexPolygon polygon = Assert.IsType(region.Shape); + + Assert.Equal(this.pen.StrokeFill, processor.Brush); + } + } + + [Fact] + public void CorrectlySetsColorAndPath() + { + this.operations.Draw(this.color, 1, this.pathCollection); + + for (int i = 0; i < 2; i++) + { + FillRegionProcessor processor = this.Verify>(i); + + Assert.Equal(GraphicsOptions.Default, processor.Options); + + ShapePath region = Assert.IsType(processor.Region); + ComplexPolygon polygon = Assert.IsType(region.Shape); + + SolidBrush brush = Assert.IsType>(processor.Brush); + Assert.Equal(this.color, brush.Color); + } + } + + [Fact] + public void CorrectlySetsColorPathAndOptions() + { + this.operations.Draw(this.noneDefault, this.color, 1, this.pathCollection); + + for (int i = 0; i < 2; i++) + { + FillRegionProcessor processor = this.Verify>(i); + + Assert.Equal(this.noneDefault, processor.Options); + + ShapePath region = Assert.IsType(processor.Region); + ComplexPolygon polygon = Assert.IsType(region.Shape); + + SolidBrush brush = Assert.IsType>(processor.Brush); + Assert.Equal(this.color, brush.Color); + } + } + } +} diff --git a/tests/ImageSharp.Tests/Drawing/Text/DrawText.Path.cs b/tests/ImageSharp.Tests/Drawing/Text/DrawText.Path.cs deleted file mode 100644 index 4649bee6b..000000000 --- a/tests/ImageSharp.Tests/Drawing/Text/DrawText.Path.cs +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright (c) Six Labors and contributors. -// Licensed under the Apache License, Version 2.0. - -using System.Numerics; -using SixLabors.Fonts; -using SixLabors.ImageSharp.PixelFormats; -using SixLabors.ImageSharp.Processing.Drawing.Brushes; -using SixLabors.ImageSharp.Processing.Drawing.Pens; -using SixLabors.ImageSharp.Processing.Drawing.Processors; -using SixLabors.ImageSharp.Processing.Text; -using SixLabors.Shapes; -using Xunit; - -namespace SixLabors.ImageSharp.Tests.Drawing.Text -{ - public class DrawText_Path : BaseImageOperationsExtensionTest - { - Rgba32 color = Rgba32.HotPink; - - SolidBrush brush = Brushes.Solid(Rgba32.HotPink); - - IPath path = new SixLabors.Shapes.Path( - new LinearLineSegment( - new SixLabors.Primitives.PointF[] { new Vector2(10, 10), new Vector2(20, 10), new Vector2(20, 10), new Vector2(30, 10), })); - - private readonly FontCollection FontCollection; - - private readonly Font Font; - - public DrawText_Path() - { - this.FontCollection = new FontCollection(); - this.Font = this.FontCollection.Install(TestFontUtilities.GetPath("SixLaborsSampleAB.woff")).CreateFont(12); - } - - [Fact] - public void FillsForEachACharachterWhenBrushSetAndNotPen() - { - this.operations.DrawText( - new TextGraphicsOptions(true), - "123", - this.Font, - Brushes.Solid(Rgba32.Red), - null, - this.path); - - this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - } - - [Fact] - public void FillsForEachACharachterWhenBrushSetAndNotPenDefaultOptions() - { - this.operations.DrawText("123", this.Font, Brushes.Solid(Rgba32.Red), null, this.path); - - this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - } - - [Fact] - public void FillsForEachACharachterWhenBrushSet() - { - this.operations.DrawText(new TextGraphicsOptions(true), "123", this.Font, Brushes.Solid(Rgba32.Red), this.path); - - this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - } - - [Fact] - public void FillsForEachACharachterWhenBrushSetDefaultOptions() - { - this.operations.DrawText("123", this.Font, Brushes.Solid(Rgba32.Red), this.path); - - this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - } - - [Fact] - public void FillsForEachACharachterWhenColorSet() - { - this.operations.DrawText(new TextGraphicsOptions(true), "123", this.Font, Rgba32.Red, this.path); - - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - - SolidBrush brush = Assert.IsType>(processor.Brush); - Assert.Equal(Rgba32.Red, brush.Color); - } - - [Fact] - public void FillsForEachACharachterWhenColorSetDefaultOptions() - { - this.operations.DrawText("123", this.Font, Rgba32.Red, this.path); - - FillRegionProcessor processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - - SolidBrush brush = Assert.IsType>(processor.Brush); - Assert.Equal(Rgba32.Red, brush.Color); - } - - [Fact] - public void DrawForEachACharachterWhenPenSetAndNotBrush() - { - this.operations.DrawText( - new TextGraphicsOptions(true), - "123", - this.Font, - null, - Pens.Dash(Rgba32.Red, 1), - this.path); - - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - } - - [Fact] - public void DrawForEachACharachterWhenPenSetAndNotBrushDefaultOptions() - { - this.operations.DrawText("123", this.Font, null, Pens.Dash(Rgba32.Red, 1), this.path); - - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - } - - [Fact] - public void DrawForEachACharachterWhenPenSet() - { - this.operations.DrawText(new TextGraphicsOptions(true), "123", this.Font, Pens.Dash(Rgba32.Red, 1), this.path); - - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - } - - [Fact] - public void DrawForEachACharachterWhenPenSetDefaultOptions() - { - this.operations.DrawText("123", this.Font, Pens.Dash(Rgba32.Red, 1), this.path); - - FillRegionProcessor processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - } - - [Fact] - public void DrawForEachACharachterWhenPenSetAndFillFroEachWhenBrushSet() - { - this.operations.DrawText( - new TextGraphicsOptions(true), - "123", - this.Font, - Brushes.Solid(Rgba32.Red), - Pens.Dash(Rgba32.Red, 1), - this.path); - - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - this.Verify>(3); - this.Verify>(4); - this.Verify>(5); - } - - [Fact] - public void DrawForEachACharachterWhenPenSetAndFillFroEachWhenBrushSetDefaultOptions() - { - this.operations.DrawText("123", this.Font, Brushes.Solid(Rgba32.Red), Pens.Dash(Rgba32.Red, 1), this.path); - - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - this.Verify>(3); - this.Verify>(4); - this.Verify>(5); - } - - [Fact] - public void BrushAppliesBeforPen() - { - this.operations.DrawText( - new TextGraphicsOptions(true), - "1", - this.Font, - Brushes.Solid(Rgba32.Red), - Pens.Dash(Rgba32.Red, 1), - this.path); - - var processor = this.Verify>(0); - this.Verify>(1); - } - - [Fact] - public void BrushAppliesBeforPenDefaultOptions() - { - this.operations.DrawText("1", this.Font, Brushes.Solid(Rgba32.Red), Pens.Dash(Rgba32.Red, 1), this.path); - - var processor = this.Verify>(0); - this.Verify>(1); - } - } -} diff --git a/tests/ImageSharp.Tests/Drawing/Text/DrawText.cs b/tests/ImageSharp.Tests/Drawing/Text/DrawText.cs index 88b650a3e..2a03eb415 100644 --- a/tests/ImageSharp.Tests/Drawing/Text/DrawText.cs +++ b/tests/ImageSharp.Tests/Drawing/Text/DrawText.cs @@ -8,6 +8,8 @@ using SixLabors.ImageSharp.Processing.Drawing.Brushes; using SixLabors.ImageSharp.Processing.Drawing.Pens; using SixLabors.ImageSharp.Processing.Drawing.Processors; using SixLabors.ImageSharp.Processing.Text; +using SixLabors.ImageSharp.Processing.Text.Processors; +using SixLabors.Primitives; using SixLabors.Shapes; using Xunit; @@ -44,9 +46,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text null, Vector2.Zero); - this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + this.Verify>(0); } [Fact] @@ -54,9 +54,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { this.operations.DrawText("123", this.Font, Brushes.Solid(Rgba32.Red), null, Vector2.Zero); - this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + this.Verify>(0); } [Fact] @@ -64,9 +62,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { this.operations.DrawText(new TextGraphicsOptions(true), "123", this.Font, Brushes.Solid(Rgba32.Red), Vector2.Zero); - this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + this.Verify>(0); } [Fact] @@ -74,9 +70,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { this.operations.DrawText("123", this.Font, Brushes.Solid(Rgba32.Red), Vector2.Zero); - this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + this.Verify>(0); } [Fact] @@ -84,9 +78,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { this.operations.DrawText(new TextGraphicsOptions(true), "123", this.Font, Rgba32.Red, Vector2.Zero); - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + var processor = this.Verify>(0); SolidBrush brush = Assert.IsType>(processor.Brush); Assert.Equal(Rgba32.Red, brush.Color); @@ -97,9 +89,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { this.operations.DrawText("123", this.Font, Rgba32.Red, Vector2.Zero); - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + var processor = this.Verify>(0); SolidBrush brush = Assert.IsType>(processor.Brush); Assert.Equal(Rgba32.Red, brush.Color); @@ -116,9 +106,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text Pens.Dash(Rgba32.Red, 1), Vector2.Zero); - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + var processor = this.Verify>(0); } [Fact] @@ -126,9 +114,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { this.operations.DrawText("123", this.Font, null, Pens.Dash(Rgba32.Red, 1), Vector2.Zero); - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + var processor = this.Verify>(0); } [Fact] @@ -136,9 +122,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { this.operations.DrawText(new TextGraphicsOptions(true), "123", this.Font, Pens.Dash(Rgba32.Red, 1), Vector2.Zero); - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + var processor = this.Verify>(0); } [Fact] @@ -146,9 +130,14 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { this.operations.DrawText("123", this.Font, Pens.Dash(Rgba32.Red, 1), Vector2.Zero); - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + var processor = this.Verify>(0); + + Assert.Equal("123", processor.Text); + Assert.Equal(this.Font, processor.Font); + var penBrush = Assert.IsType>(processor.Pen.StrokeFill); + Assert.Equal(Rgba32.Red, penBrush.Color); + Assert.Equal(1, processor.Pen.StrokeWidth); + Assert.Equal(PointF.Empty, processor.Location); } [Fact] @@ -162,50 +151,16 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text Pens.Dash(Rgba32.Red, 1), Vector2.Zero); - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - - this.Verify>(3); - this.Verify>(4); - this.Verify>(5); - } - - [Fact] - public void DrawForEachACharachterWhenPenSetAndFillFroEachWhenBrushSetDefaultOptions() - { - this.operations.DrawText("123", this.Font, Brushes.Solid(Rgba32.Red), Pens.Dash(Rgba32.Red, 1), Vector2.Zero); - - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - this.Verify>(3); - this.Verify>(4); - this.Verify>(5); - } - - [Fact] - public void BrushAppliesBeforePen() - { - this.operations.DrawText( - new TextGraphicsOptions(true), - "1", - this.Font, - Brushes.Solid(Rgba32.Red), - Pens.Dash(Rgba32.Red, 1), - Vector2.Zero); - - var processor = this.Verify>(0); - this.Verify>(1); - } + var processor = this.Verify>(0); - [Fact] - public void BrushAppliesBeforPenDefaultOptions() - { - this.operations.DrawText("1", this.Font, Brushes.Solid(Rgba32.Red), Pens.Dash(Rgba32.Red, 1), Vector2.Zero); - - var processor = this.Verify>(0); - this.Verify>(1); + Assert.Equal("123", processor.Text); + Assert.Equal(this.Font, processor.Font); + var brush = Assert.IsType>(processor.Brush); + Assert.Equal(Rgba32.Red, brush.Color); + Assert.Equal(PointF.Empty, processor.Location); + var penBrush = Assert.IsType>(processor.Pen.StrokeFill); + Assert.Equal(Rgba32.Red, penBrush.Color); + Assert.Equal(1, processor.Pen.StrokeWidth); } } } diff --git a/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs index a9c7a6ebb..7c04d090b 100644 --- a/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs +++ b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs @@ -1,25 +1,22 @@ // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -using System.Numerics; - +using System; +using System.Linq; +using System.Text; using SixLabors.Fonts; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; -using SixLabors.ImageSharp.Processing.Drawing; +using SixLabors.ImageSharp.Processing.Drawing.Pens; using SixLabors.ImageSharp.Processing.Text; +using SixLabors.ImageSharp.Tests.TestUtilities.ImageComparison; +using SixLabors.Primitives; using Xunit; // ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Drawing.Text { - using System; - using System.Linq; - using System.Text; - - using SixLabors.Primitives; - [GroupOutput("Drawing/Text")] public class DrawTextOnImageTests { @@ -27,9 +24,9 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text private const string TestText = "Sphinx of black quartz, judge my vow\n0123456789"; - private const string TestText2 = - "THISISTESTWORDS "; - + public static ImageComparer TextDrawingComparer = ImageComparer.TolerantPercentage(0.01f); + public static ImageComparer OutlinedTextDrawingComparer = ImageComparer.TolerantPercentage(0.5f, 3); + [Theory] [WithSolidFilledImages(200, 100, "White", PixelTypes.Rgba32, 50, 0, 0, "SixLaborsSampleAB.woff", AB)] [WithSolidFilledImages(900, 100, "White", PixelTypes.Rgba32, 50, 0, 0, "OpenSans-Regular.ttf", TestText)] @@ -45,16 +42,15 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text where TPixel : struct, IPixel { Font font = CreateFont(fontName, fontSize); - string fnDisplayText = text.Replace("\n", ""); - fnDisplayText = fnDisplayText.Substring(0, Math.Min(fnDisplayText.Length, 4)); TPixel color = NamedColors.Black; provider.VerifyOperation( + TextDrawingComparer, img => - { - img.Mutate(c => c.DrawText(text, new Font(font, fontSize), color, new PointF(x, y))); - }, - $"{fontName}-{fontSize}-{fnDisplayText}-({x},{y})", + { + img.Mutate(c => c.DrawText(text, new Font(font, fontSize), color, new PointF(x, y))); + }, + $"{fontName}-{fontSize}-{ToTestOutputDisplayText(text)}-({x},{y})", appendPixelTypeToFileName: false, appendSourceFileOrDescription: true); } @@ -84,15 +80,16 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text } var textOptions = new TextGraphicsOptions - { - Antialias = true, - ApplyKerning = true, - VerticalAlignment = VerticalAlignment.Top, - HorizontalAlignment = HorizontalAlignment.Left, - }; + { + Antialias = true, + ApplyKerning = true, + VerticalAlignment = VerticalAlignment.Top, + HorizontalAlignment = HorizontalAlignment.Left, + }; TPixel color = NamedColors.Black; provider.VerifyOperation( + TextDrawingComparer, img => { img.Mutate(c => c.DrawText(textOptions, sb.ToString(), font, color, new PointF(10, 5))); @@ -101,8 +98,69 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text false); } + [Theory] + [WithSolidFilledImages(200, 100, "White", PixelTypes.Rgba32, 50, 0, 0, "SixLaborsSampleAB.woff", AB)] + [WithSolidFilledImages(900, 100, "White", PixelTypes.Rgba32, 50, 0, 0, "OpenSans-Regular.ttf", TestText)] + [WithSolidFilledImages(1100, 200, "White", PixelTypes.Rgba32, 50, 150, 100, "OpenSans-Regular.ttf", TestText)] + public void FontShapesAreRenderedCorrectlyWithAPen( + TestImageProvider provider, + int fontSize, + int x, + int y, + string fontName, + string text) + where TPixel : struct, IPixel + { + Font font = CreateFont(fontName, fontSize); + TPixel color = NamedColors.Black; + + provider.VerifyOperation( + OutlinedTextDrawingComparer, + img => + { + img.Mutate(c => c.DrawText(text, new Font(font, fontSize), null, Pens.Solid(color, 1), new PointF(x, y))); + }, + $"pen_{fontName}-{fontSize}-{ToTestOutputDisplayText(text)}-({x},{y})", + appendPixelTypeToFileName: false, + appendSourceFileOrDescription: true); + } + + [Theory] + [WithSolidFilledImages(200, 100, "White", PixelTypes.Rgba32, 50, 0, 0, "SixLaborsSampleAB.woff", AB)] + [WithSolidFilledImages(900, 100, "White", PixelTypes.Rgba32, 50, 0, 0, "OpenSans-Regular.ttf", TestText)] + [WithSolidFilledImages(1100, 200, "White", PixelTypes.Rgba32, 50, 150, 100, "OpenSans-Regular.ttf", TestText)] + public void FontShapesAreRenderedCorrectlyWithAPenPatterned( + TestImageProvider provider, + int fontSize, + int x, + int y, + string fontName, + string text) + where TPixel : struct, IPixel + { + Font font = CreateFont(fontName, fontSize); + TPixel color = NamedColors.Black; + + provider.VerifyOperation( + OutlinedTextDrawingComparer, + img => + { + img.Mutate(c => c.DrawText(text, new Font(font, fontSize), null, Pens.DashDot(color, 3), new PointF(x, y))); + }, + $"pen_{fontName}-{fontSize}-{ToTestOutputDisplayText(text)}-({x},{y})", + appendPixelTypeToFileName: false, + appendSourceFileOrDescription: true); + } + private static string Repeat(string str, int times) => string.Concat(Enumerable.Repeat(str, times)); + private static string ToTestOutputDisplayText(string text) + { + string fnDisplayText = text.Replace("\n", ""); + fnDisplayText = fnDisplayText.Substring(0, Math.Min(fnDisplayText.Length, 4)); + return fnDisplayText; + } + private static Font CreateFont(string fontName, int size) { var fontCollection = new FontCollection(); diff --git a/tests/ImageSharp.Tests/Drawing/Utils/QuickSortTests.cs b/tests/ImageSharp.Tests/Drawing/Utils/QuickSortTests.cs new file mode 100644 index 000000000..6660cd87a --- /dev/null +++ b/tests/ImageSharp.Tests/Drawing/Utils/QuickSortTests.cs @@ -0,0 +1,51 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +namespace SixLabors.ImageSharp.Tests.Drawing.Utils +{ + using System; + using System.Linq; + + using SixLabors.ImageSharp.Utils; + + using Xunit; + + public class QuickSortTests + { + public static readonly TheoryData Data = new TheoryData() + { + new float[]{ 3, 2, 1 }, + new float[0], + new float[] { 42}, + new float[] { 1, 2}, + new float[] { 2, 1}, + new float[] { 5, 1, 2, 3, 0} + }; + + [Theory] + [MemberData(nameof(Data))] + public void Sort(float[] data) + { + float[] expected = data.ToArray(); + + Array.Sort(expected); + + QuickSort.Sort(data); + + Assert.Equal(expected, data); + } + + [Fact] + public void SortSlice() + { + float[] data = { 3, 2, 1, 0, -1 }; + + Span slice = data.AsSpan(1, 3); + QuickSort.Sort(slice); + float[] actual = slice.ToArray(); + float[] expected = { 0, 1, 2 }; + + Assert.Equal(actual, expected); + } + } +} \ No newline at end of file diff --git a/tests/ImageSharp.Tests/Formats/Png/PngChunkTypeTests.cs b/tests/ImageSharp.Tests/Formats/Png/PngChunkTypeTests.cs index 016c932dd..35652dd6b 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngChunkTypeTests.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngChunkTypeTests.cs @@ -19,6 +19,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png Assert.Equal(PngChunkType.Text, GetType("tEXt")); Assert.Equal(PngChunkType.Gamma, GetType("gAMA")); Assert.Equal(PngChunkType.Physical, GetType("pHYs")); + Assert.Equal(PngChunkType.Exif, GetType("eXIf")); } private static PngChunkType GetType(string text) diff --git a/tests/ImageSharp.Tests/ImageSharp.Tests.csproj b/tests/ImageSharp.Tests/ImageSharp.Tests.csproj index 139df3972..ad8b79e5d 100644 --- a/tests/ImageSharp.Tests/ImageSharp.Tests.csproj +++ b/tests/ImageSharp.Tests/ImageSharp.Tests.csproj @@ -25,6 +25,7 @@ + @@ -34,7 +35,7 @@ - + @@ -45,6 +46,12 @@ + + PreserveNewest + + + PreserveNewest + PreserveNewest diff --git a/tests/ImageSharp.Tests/TestUtilities/TestEnvironment.cs b/tests/ImageSharp.Tests/TestUtilities/TestEnvironment.cs index 4cee650e8..b07a383b7 100644 --- a/tests/ImageSharp.Tests/TestUtilities/TestEnvironment.cs +++ b/tests/ImageSharp.Tests/TestUtilities/TestEnvironment.cs @@ -30,6 +30,13 @@ namespace SixLabors.ImageSharp.Tests return Boolean.TryParse(Environment.GetEnvironmentVariable("CI"), out isCi) && isCi; }); + private static readonly Lazy NetCoreVersionLazy = new Lazy(GetNetCoreVersion); + + /// + /// Gets the .NET Core version, if running on .NET Core, otherwise returns an empty string. + /// + internal static string NetCoreVersion => NetCoreVersionLazy.Value; + // ReSharper disable once InconsistentNaming /// /// Gets a value indicating whether test execution runs on CI. @@ -123,5 +130,19 @@ namespace SixLabors.ImageSharp.Tests return path; } + + /// + /// Solution borrowed from: + /// https://github.com/dotnet/BenchmarkDotNet/issues/448#issuecomment-308424100 + /// + private static string GetNetCoreVersion() + { + Assembly assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly; + string[] assemblyPath = assembly.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries); + int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App"); + if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2) + return assemblyPath[netCoreAppIndex + 1]; + return ""; + } } } \ No newline at end of file diff --git a/tests/ImageSharp.Tests/TestUtilities/Tests/TestEnvironmentTests.cs b/tests/ImageSharp.Tests/TestUtilities/Tests/TestEnvironmentTests.cs index 9db55281e..4a2c63beb 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Tests/TestEnvironmentTests.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Tests/TestEnvironmentTests.cs @@ -4,6 +4,7 @@ using System; using System.IO; +using SixLabors.ImageSharp.Common.Helpers; using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.Formats.Bmp; using SixLabors.ImageSharp.Formats.Gif; @@ -13,9 +14,11 @@ using SixLabors.ImageSharp.Tests.TestUtilities.ReferenceCodecs; using Xunit; using Xunit.Abstractions; +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests { + public class TestEnvironmentTests { public TestEnvironmentTests(ITestOutputHelper output) @@ -31,6 +34,29 @@ namespace SixLabors.ImageSharp.Tests Assert.True(Directory.Exists(path)); } + /// + /// We need this test to make sure that the netcoreapp2.1 test execution actually covers the netcoreapp2.1 build configuration of ImageSharp. + /// + [Fact] + public void ImageSharpAssemblyUnderTest_MatchesExpectedTargetFramework() + { + this.Output.WriteLine("NetCoreVersion: " + TestEnvironment.NetCoreVersion); + this.Output.WriteLine("ImageSharpBuiltAgainst: " + TestHelpers.ImageSharpBuiltAgainst); + + if (string.IsNullOrEmpty(TestEnvironment.NetCoreVersion)) + { + this.Output.WriteLine("Not running under .NET Core!"); + } + else if (TestEnvironment.NetCoreVersion.StartsWith("2.1")) + { + Assert.Equal("netcoreapp2.1", TestHelpers.ImageSharpBuiltAgainst); + } + else + { + Assert.Equal("netstandard2.0", TestHelpers.ImageSharpBuiltAgainst); + } + } + [Fact] public void SolutionDirectoryFullPath() {