Skip to content

Handle hex parsing in Color with format support #2964

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโ€™ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Aug 11, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
274 changes: 231 additions & 43 deletions src/ImageSharp/Color/Color.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.

using System.Buffers.Binary;
using System.Globalization;
using System.Numerics;
using System.Runtime.CompilerServices;
using SixLabors.ImageSharp.PixelFormats;
Expand Down Expand Up @@ -126,66 +128,91 @@ public static void FromPixel<TPixel>(ReadOnlySpan<TPixel> source, Span<Color> de
}

/// <summary>
/// Creates a new instance of the <see cref="Color"/> struct
/// from the given hexadecimal string.
/// Gets a <see cref="Color"/> from the given hexadecimal string.
/// </summary>
/// <param name="hex">
/// The hexadecimal representation of the combined color components arranged
/// in rgb, rgba, rrggbb, or rrggbbaa format to match web syntax.
/// The hexadecimal representation of the combined color components.
/// </param>
/// <param name="format">
/// The format of the hexadecimal string to parse, if applicable. Defaults to <see cref="ColorHexFormat.Rgba"/>.
/// </param>
/// <returns>
/// The <see cref="Color"/>.
/// The <see cref="Color"/> equivalent of the hexadecimal input.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Color ParseHex(string hex)
/// <exception cref="ArgumentException">
/// Thrown when the <paramref name="hex"/> is not in the correct format.
/// </exception>
public static Color ParseHex(string hex, ColorHexFormat format = ColorHexFormat.Rgba)
{
Rgba32 rgba = Rgba32.ParseHex(hex);
return FromPixel(rgba);
Guard.NotNull(hex, nameof(hex));

if (!TryParseHex(hex, out Color color, format))
{
throw new ArgumentException("Hexadecimal string is not in the correct format.", nameof(hex));
}

return color;
}

/// <summary>
/// Attempts to creates a new instance of the <see cref="Color"/> struct
/// from the given hexadecimal string.
/// Gets a <see cref="Color"/> from the given hexadecimal string.
/// </summary>
/// <param name="hex">
/// The hexadecimal representation of the combined color components arranged
/// in rgb, rgba, rrggbb, or rrggbbaa format to match web syntax.
/// The hexadecimal representation of the combined color components.
/// </param>
/// <param name="result">
/// When this method returns, contains the <see cref="Color"/> equivalent of the hexadecimal input.
/// </param>
/// <param name="format">
/// The format of the hexadecimal string to parse, if applicable. Defaults to <see cref="ColorHexFormat.Rgba"/>.
/// </param>
/// <param name="result">When this method returns, contains the <see cref="Color"/> equivalent of the hexadecimal input.</param>
/// <returns>
/// The <see cref="bool"/>.
/// <see langword="true"/> if the parsing was successful; otherwise, <see langword="false"/>.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryParseHex(string hex, out Color result)
public static bool TryParseHex(string hex, out Color result, ColorHexFormat format = ColorHexFormat.Rgba)
{
result = default;

if (Rgba32.TryParseHex(hex, out Rgba32 rgba))
if (format == ColorHexFormat.Argb)
{
result = FromPixel(rgba);
return true;
if (TryParseArgbHex(hex, out Argb32 argb))
{
result = FromPixel(argb);
return true;
}
}
else if (format == ColorHexFormat.Rgba)
{
if (TryParseRgbaHex(hex, out Rgba32 rgba))
{
result = FromPixel(rgba);
return true;
}
}

return false;
}

/// <summary>
/// Creates a new instance of the <see cref="Color"/> struct
/// from the given input string.
/// Gets a <see cref="Color"/> from the given input string.
/// </summary>
/// <param name="input">
/// The name of the color or the hexadecimal representation of the combined color components arranged
/// in rgb, rgba, rrggbb, or rrggbbaa format to match web syntax.
/// The name of the color or the hexadecimal representation of the combined color components.
/// </param>
/// <param name="format">
/// The format of the hexadecimal string to parse, if applicable. Defaults to <see cref="ColorHexFormat.Rgba"/>.
/// </param>
/// <returns>
/// The <see cref="Color"/>.
/// The <see cref="Color"/> equivalent of the input string.
/// </returns>
/// <exception cref="ArgumentException">Input string is not in the correct format.</exception>
public static Color Parse(string input)
/// <exception cref="ArgumentException">
/// Thrown when the <paramref name="input"/> is not in the correct format.
/// </exception>
public static Color Parse(string input, ColorHexFormat format = ColorHexFormat.Rgba)
{
Guard.NotNull(input, nameof(input));

if (!TryParse(input, out Color color))
if (!TryParse(input, out Color color, format))
{
throw new ArgumentException("Input string is not in the correct format.", nameof(input));
}
Expand All @@ -194,18 +221,21 @@ public static Color Parse(string input)
}

/// <summary>
/// Attempts to creates a new instance of the <see cref="Color"/> struct
/// from the given input string.
/// Tries to create a new instance of the <see cref="Color"/> struct from the given input string.
/// </summary>
/// <param name="input">
/// The name of the color or the hexadecimal representation of the combined color components arranged
/// in rgb, rgba, rrggbb, or rrggbbaa format to match web syntax.
/// The name of the color or the hexadecimal representation of the combined color components.
/// </param>
/// <param name="result">
/// When this method returns, contains the <see cref="Color"/> equivalent of the input string.
/// </param>
/// <param name="format">
/// The format of the hexadecimal string to parse, if applicable. Defaults to <see cref="ColorHexFormat.Rgba"/>.
/// </param>
/// <param name="result">When this method returns, contains the <see cref="Color"/> equivalent of the hexadecimal input.</param>
/// <returns>
/// The <see cref="bool"/>.
/// <see langword="true"/> if the parsing was successful; otherwise, <see langword="false"/>.
/// </returns>
public static bool TryParse(string input, out Color result)
public static bool TryParse(string input, out Color result, ColorHexFormat format = ColorHexFormat.Rgba)
{
result = default;

Expand All @@ -219,14 +249,21 @@ public static bool TryParse(string input, out Color result)
return true;
}

return TryParseHex(input, out result);
result = default;
if (string.IsNullOrWhiteSpace(input))
{
return false;
}

return TryParseHex(input, out result, format);
}

/// <summary>
/// Alters the alpha channel of the color, returning a new instance.
/// </summary>
/// <param name="alpha">The new value of alpha [0..1].</param>
/// <returns>The color having it's alpha channel altered.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Color WithAlpha(float alpha)
{
Vector4 v = this.ToScaledVector4();
Expand All @@ -235,22 +272,32 @@ public Color WithAlpha(float alpha)
}

/// <summary>
/// Gets the hexadecimal representation of the color instance in rrggbbaa form.
/// Gets the hexadecimal string representation of the color instance.
/// </summary>
/// <param name="format">
/// The format of the hexadecimal string to return. Defaults to <see cref="ColorHexFormat.Rgba"/>.
/// </param>
/// <returns>A hexadecimal string representation of the value.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the <paramref name="format"/> is not supported.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public string ToHex()
public string ToHex(ColorHexFormat format = ColorHexFormat.Rgba)
{
if (this.boxedHighPrecisionPixel is not null)
Rgba32 rgba = (this.boxedHighPrecisionPixel is not null)
? this.boxedHighPrecisionPixel.ToRgba32()
: Rgba32.FromScaledVector4(this.data);

uint hexOrder = format switch
{
return this.boxedHighPrecisionPixel.ToRgba32().ToHex();
}
ColorHexFormat.Argb => (uint)((rgba.B << 0) | (rgba.G << 8) | (rgba.R << 16) | (rgba.A << 24)),
ColorHexFormat.Rgba => (uint)((rgba.A << 0) | (rgba.B << 8) | (rgba.G << 16) | (rgba.R << 24)),
_ => throw new ArgumentOutOfRangeException(nameof(format), format, "Unsupported color hex format.")
};

return Rgba32.FromScaledVector4(this.data).ToHex();
return hexOrder.ToString("X8", CultureInfo.InvariantCulture);
}

/// <inheritdoc />
public override string ToString() => this.ToHex();
public override string ToString() => this.ToHex(ColorHexFormat.Rgba);

/// <summary>
/// Converts the color instance to a specified <typeparamref name="TPixel"/> type.
Expand Down Expand Up @@ -336,4 +383,145 @@ public override int GetHashCode()

return this.boxedHighPrecisionPixel.GetHashCode();
}

/// <summary>
/// Gets the hexadecimal string representation of the color instance in the format RRGGBBAA.
/// </summary>
/// <param name="hex">
/// The hexadecimal representation of the combined color components.
/// </param>
/// <param name="result">
/// When this method returns, contains the <see cref="Rgba32"/> equivalent of the hexadecimal input.
/// </param>
/// <returns>
/// <see langword="true"/> if the parsing was successful; otherwise, <see langword="false"/>.
/// </returns>
private static bool TryParseRgbaHex(string? hex, out Rgba32 result)
{
result = default;
if (string.IsNullOrWhiteSpace(hex))
{
return false;
}

ReadOnlySpan<char> hexSpan = ToRgbaHex(hex);

if (!uint.TryParse(hexSpan, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint packedValue))
{
return false;
}

packedValue = BinaryPrimitives.ReverseEndianness(packedValue);
result = Unsafe.As<uint, Rgba32>(ref packedValue);
return true;
}

/// <summary>
/// Gets the hexadecimal string representation of the color instance in the format AARRGGBB.
/// </summary>
/// <param name="hex">
/// The hexadecimal representation of the combined color components.
/// </param>
/// <param name="result">
/// When this method returns, contains the <see cref="Argb32"/> equivalent of the hexadecimal input.
/// </param>
/// <returns>
/// <see langword="true"/> if the parsing was successful; otherwise, <see langword="false"/>.
/// </returns>
private static bool TryParseArgbHex(string? hex, out Argb32 result)
{
result = default;
if (string.IsNullOrWhiteSpace(hex))
{
return false;
}

ReadOnlySpan<char> hexSpan = ToArgbHex(hex);

if (!uint.TryParse(hexSpan, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint packedValue))
{
return false;
}

packedValue = BinaryPrimitives.ReverseEndianness(packedValue);
result = Unsafe.As<uint, Argb32>(ref packedValue);
return true;
}

/// <summary>
/// Converts the specified hex value to an RRGGBBAA hex value.
/// </summary>
/// <param name="value">The hex value to convert.</param>
/// <returns>
/// A span containing the converted hex value in the format RRGGBBAA.
/// </returns>
private static ReadOnlySpan<char> ToRgbaHex(string value)
{
ReadOnlySpan<char> hex = value.AsSpan();

if (hex[0] == '#')
{
hex = hex[1..];
}

if (hex.Length == 8)
{
return hex;
}

if (hex.Length == 6)
{
return $"{hex}FF";
}

if (hex.Length is < 3 or > 4)
{
return null;
}

char a = hex.Length == 3 ? 'F' : hex[3];
char b = hex[2];
char g = hex[1];
char r = hex[0];

return new string([r, r, g, g, b, b, a, a]);
}

/// <summary>
/// Converts the specified hex value to an AARRGGBB hex value.
/// </summary>
/// <param name="value">The hex value to convert.</param>
/// <returns>
/// A span containing the converted hex value in the format AARRGGBB.
/// </returns>
private static ReadOnlySpan<char> ToArgbHex(string value)
{
ReadOnlySpan<char> hex = value.AsSpan();

if (hex[0] == '#')
{
hex = hex[1..];
}

if (hex.Length == 8)
{
return hex;
}

if (hex.Length == 6)
{
return $"FF{hex}";
}

if (hex.Length is < 3 or > 4)
{
return null;
}

(char a, char r, char g, char b) = hex.Length == 3
? ('F', hex[0], hex[1], hex[2])
: (hex[0], hex[1], hex[2], hex[3]);

return new string([a, a, r, r, g, g, b, b]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similar to #2963 (comment), I'd use string.Create here (note: due the collection expression, C# will emit a inline here and no allocation happens, but it's unneded copying around the value).

Copy link

@lindexi lindexi Jul 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gfoidl I wrote the faster one:

static (bool success, byte a, byte r, byte g, byte b) ConvertToColor(string input) //ARGB format
{
    bool startWithPoundSign = input.StartsWith('#');
    var colorStringLength = input.Length;
    if (startWithPoundSign) colorStringLength -= 1;
    int currentOffset = startWithPoundSign ? 1 : 0;
    // Formats:
    // #FFDFD991   8 chars with Alpha
    // #DFD991     6 chars
    // #FD92       4 chars with Alpha
    // #DAC        3 chars
    if (colorStringLength == 8
        || colorStringLength == 6
        || colorStringLength == 4
        || colorStringLength == 3)
    {
        bool success;
        byte result;
        byte a;

        int readCount;
        // #DFD991     6 chars
        // #FFDFD991   8 chars with Alpha
        //if (colorStringLength == 8 || colorStringLength == 6)
        if (colorStringLength > 5)
        {
            readCount = 2;
        }
        else
        {
            readCount = 1;
        }

        bool includeAlphaChannel = colorStringLength == 8 || colorStringLength == 4;

        if (includeAlphaChannel)
        {
            (success, result) = HexCharToNumber(input, currentOffset, readCount);
            if (!success) return default;
            a = result;
            currentOffset += readCount;
        }
        else
        {
            a = 0xFF;
        }

        (success, result) = HexCharToNumber(input, currentOffset, readCount);
        if (!success) return default;
        byte r = result;
        currentOffset += readCount;

        (success, result) = HexCharToNumber(input, currentOffset, readCount);
        if (!success) return default;
        byte g = result;
        currentOffset += readCount;

        (success, result) = HexCharToNumber(input, currentOffset, readCount);
        if (!success) return default;
        byte b = result;

        return (true, a, r, g, b);
    }

    return default;
}

static (bool success, byte result) HexCharToNumber(string input, int offset, int readCount)
{
    Debug.Assert(readCount == 1 || readCount == 2);

    byte result = 0;

    for (int i = 0; i < readCount; i++, offset++)
    {
        var c = input[offset];
        byte n;
        if (c >= '0' && c <= '9')
        {
            n = (byte)(c - '0');
        }
        else if (c >= 'a' && c <= 'f')
        {
            n = (byte)(c - 'a' + 10);
        }
        else if (c >= 'A' && c <= 'F')
        {
            n = (byte)(c - 'A' + 10);
        }
        else
        {
            return default;
        }

        result *= 16;
        result += n;
    }

    if (readCount == 1)
    {
        result = (byte)(result * 16 + result);
    }

    return (true, result);
}

We parse to string, and then parse string to uint. In fact, we can achieve zero alloc.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

๐Ÿ‘๐Ÿป

Instead of the if (c >= 'a' && c <= 'f') you can use pattern matching (is), as Roslyn will emit optimized tests (at least in a future version, but some of them are already enabled).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dammit you nerd sniped me!! ๐Ÿคฃ

I've updated the code to use a zero-allocation implementation for both RGBA and ARGB layout.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JimBobSquarePants The code I shown is the zero-allocation implementation. See my benchmark for the code I shown, and you can find my benchmark code in https://github.com/lindexi/lindexi_gd/blob/8422ee2ff82386e57eeb8bb43735a7ef3121782f/Workbench/RenalwhuchewelneHukawine/ColorParserBenchmark.cs

Method colorText Mean Error StdDev Allocated
Test #123456 4.8096 ns 0.0112 ns 0.0105 ns -
Test #AABBCC 5.3978 ns 0.0150 ns 0.0141 ns -
Test #AABBCC1 0.3928 ns 0.0059 ns 0.0055 ns -
Test #AABBCCDD 6.7899 ns 0.0187 ns 0.0175 ns -
Test #ABC 3.9403 ns 0.0245 ns 0.0217 ns -
Test #FF123456 6.3917 ns 0.0213 ns 0.0189 ns -
Test #FFAABBCC 6.7806 ns 0.0152 ns 0.0143 ns -
Test #FFAABBCC1 0.3235 ns 0.0033 ns 0.0031 ns -

The origin code in ImageSharp should alloc some memory.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you may have misunderstood what I said. The code in this PR is now zero allocation for both RGBA and ARGB scenarios.

}
}
Loading
Loading