From fda2d1fc04ffa94aeaada4ef313b88bec6ca74a6 Mon Sep 17 00:00:00 2001 From: Jason Nelson Date: Thu, 10 May 2018 08:21:33 -0700 Subject: [PATCH] Optimize ColorBuilder --- .../PixelFormats/ColorBuilder{TPixel}.cs | 21 ++++++++----------- 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/src/ImageSharp/PixelFormats/ColorBuilder{TPixel}.cs b/src/ImageSharp/PixelFormats/ColorBuilder{TPixel}.cs index 1e7645aeb..c2c0277f9 100644 --- a/src/ImageSharp/PixelFormats/ColorBuilder{TPixel}.cs +++ b/src/ImageSharp/PixelFormats/ColorBuilder{TPixel}.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. using System; +using System.Buffers.Binary; using System.Globalization; namespace SixLabors.ImageSharp.PixelFormats @@ -26,18 +27,14 @@ namespace SixLabors.ImageSharp.PixelFormats Guard.NotNullOrWhiteSpace(hex, nameof(hex)); hex = ToRgbaHex(hex); - uint packedValue; - if (hex == null || !uint.TryParse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out packedValue)) + + if (hex == null || !uint.TryParse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint packedValue)) { throw new ArgumentException("Hexadecimal string is not in the correct format.", nameof(hex)); } TPixel result = default; - var rgba = new Rgba32( - (byte)(packedValue >> 24), - (byte)(packedValue >> 16), - (byte)(packedValue >> 8), - (byte)(packedValue >> 0)); + var rgba = new Rgba32(BinaryPrimitives.ReverseEndianness(packedValue)); result.PackFromRgba32(rgba); return result; @@ -96,12 +93,12 @@ namespace SixLabors.ImageSharp.PixelFormats return null; } - string red = char.ToString(hex[0]); - string green = char.ToString(hex[1]); - string blue = char.ToString(hex[2]); - string alpha = hex.Length == 3 ? "F" : char.ToString(hex[3]); + char r = hex[0]; + char g = hex[1]; + char b = hex[2]; + char a = hex.Length == 3 ? 'F' : hex[3]; - return string.Concat(red, red, green, green, blue, blue, alpha, alpha); + return new string(new[] { r, r, g, g, b, b, a, a }); } } } \ No newline at end of file