Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
To extract SVG colors in C#, load the file with
SVGDocument, select elements with
QuerySelectorAll(), read fill, stroke, stop-color, and style values with
GetAttribute(), and collect unique color values. Use
Color.FromString() when you need normalized HEX output.
This article shows how to extract colors from an SVG file using Aspose.SVG for .NET. It focuses on color audit workflows: finding all colors used in an SVG, building a unique color palette, detecting gradient colors, and preparing SVG assets for later recoloring or validation.
You will learn how to:
fill, stroke, and stop-color attributes.none, currentColor, and url(#gradient).style attributes.The examples use the Aspose.SVG DOM API to inspect SVG markup and the drawing API to normalize color values:
| API | Used for |
|---|---|
| SVGDocument | Loads the SVG file and gives access to the document tree |
| Element | Represents SVG elements returned by selectors |
| QuerySelectorAll() | Selects all SVG elements, elements with inline styles, or gradient stop elements |
| GetAttribute() | Reads fill, stroke, stop-color, and style attribute values |
| Color | Parses and converts extracted color strings |
| Color.FromString() | Creates a Color object from a named color, HEX, RGB, or another supported color value |
| ToRgbHexString() | Converts a parsed color to HEX output |
Extracting colors is useful when you need to inspect SVG assets before changing or publishing them. Common scenarios include:
If you already know which colors to replace, see Replace SVG Colors in C#. This article focuses only on reading and listing colors.
The examples use
replace-svg-colors.svg, a small SVG file that contains colors in presentation attributes, gradient stops, and inline style attributes.
| SVG fragment | Where the color is stored | How the examples handle it |
|---|---|---|
stroke="grey" | SVG presentation attribute | Extracted by the attribute example |
stop-color="bisque" | Gradient stop attribute | Extracted by the attribute and gradient examples |
stop-color="grey" | Gradient stop attribute | Extracted by the attribute and gradient examples |
stop-color="silver" | Gradient stop attribute | Extracted by the attribute and gradient examples |
style="stroke: grey; stroke-width:3" | Inline CSS declaration | Extracted by the inline style example |
fill="none" | Paint keyword | Skipped because it is not a visible color |
fill="url(#myRG)" | Paint server reference | Skipped as an element color; gradient stops are inspected instead |
This distinction matters because SVG color extraction is not a single lookup. A visible SVG color may be stored directly on an element, inside a gradient definition, or inside a CSS declaration.
The following example extracts unique color values from common SVG color attributes: fill, stroke, and stop-color. It uses
QuerySelectorAll("*") to inspect every SVG element and
GetAttribute() to read each candidate color attribute. It skips values that are not direct colors, such as none, currentColor, and url(#myRG).
Use this approach when you want a quick inventory of colors stored directly in SVG markup. It is a good first pass for generated SVG files and for simple graphics where colors are defined as presentation attributes.
1using Aspose.Svg;
2using Aspose.Svg.Dom;
3using System;
4using System.Collections.Generic;
5using System.IO; 1// Extract unique SVG colors from fill, stroke, and stop-color attributes in C#
2
3// Load the source SVG file
4using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "replace-svg-colors.svg")))
5{
6 // Inspect attributes that commonly store visible SVG colors
7 string[] colorAttributes = { "fill", "stroke", "stop-color" };
8
9 // Use a case-insensitive set to keep only unique color values
10 SortedSet<string> colors = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
11
12 // Find all SVG elements and read their color-related attributes
13 foreach (Element element in document.QuerySelectorAll("*"))
14 {
15 foreach (string attributeName in colorAttributes)
16 {
17 string value = element.GetAttribute(attributeName);
18
19 if (string.IsNullOrWhiteSpace(value))
20 {
21 continue;
22 }
23
24 string color = value.Trim();
25
26 // Skip paint keywords and paint server references that are not direct colors
27 if (color.Equals("none", StringComparison.OrdinalIgnoreCase) ||
28 color.Equals("currentColor", StringComparison.OrdinalIgnoreCase) ||
29 color.StartsWith("url(", StringComparison.OrdinalIgnoreCase))
30 {
31 continue;
32 }
33
34 colors.Add(color);
35 }
36 }
37
38 // Print the unique SVG colors found in attributes
39 foreach (string color in colors)
40 {
41 Console.WriteLine(color);
42 }
43}For the sample file, this code finds colors such as grey, bisque, and silver. It does not treat fill="url(#myRG)" as a color because that value points to a gradient definition.
Expected console output:
1bisque
2grey
3silverSome SVG files store colors inside inline CSS:
1<path style="stroke: grey; stroke-width:3" fill="url(#myRG)" />In this case, stroke is not an SVG attribute. It is a CSS declaration inside the style attribute. The following example uses
QuerySelectorAll("[style]") to select only elements with inline styles, then reads the full style string with
GetAttribute(“style”).
This second pass is important for SVG files exported by design tools, where colors are often written as CSS declarations rather than presentation attributes.
1using Aspose.Svg;
2using Aspose.Svg.Dom;
3using System;
4using System.Collections.Generic;
5using System.IO; 1// Extract SVG colors from inline CSS style attributes in C#
2
3// Load the source SVG file
4using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "replace-svg-colors.svg")))
5{
6 // Inspect CSS properties that commonly store visible SVG colors
7 HashSet<string> colorProperties = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
8 {
9 "fill",
10 "stroke",
11 "color",
12 "stop-color"
13 };
14
15 SortedSet<string> colors = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
16
17 // Select only elements with inline style attributes
18 foreach (Element element in document.QuerySelectorAll("[style]"))
19 {
20 string style = element.GetAttribute("style");
21
22 // Split the inline style into individual CSS declarations
23 foreach (string declaration in style.Split(';', StringSplitOptions.RemoveEmptyEntries))
24 {
25 string[] parts = declaration.Split(':', 2);
26
27 if (parts.Length != 2)
28 {
29 continue;
30 }
31
32 string property = parts[0].Trim();
33 string value = parts[1].Trim();
34
35 if (!colorProperties.Contains(property))
36 {
37 continue;
38 }
39
40 // Skip paint keywords and paint server references that are not direct colors
41 if (value.Equals("none", StringComparison.OrdinalIgnoreCase) ||
42 value.Equals("currentColor", StringComparison.OrdinalIgnoreCase) ||
43 value.StartsWith("url(", StringComparison.OrdinalIgnoreCase))
44 {
45 continue;
46 }
47
48 colors.Add(value);
49 }
50 }
51
52 // Print the unique SVG colors found in inline styles
53 foreach (string color in colors)
54 {
55 Console.WriteLine(color);
56 }
57}This example reads inline style colors without changing the SVG document. For editing style values after inspection, see Modify SVG Styles Programmatically in C#.
For the sample file, the inline style pass extracts grey from style="stroke: grey; stroke-width:3" and ignores stroke-width because it is not a color property.
When an SVG element uses fill="url(#myRG)", the visible colors are stored inside the referenced gradient, not on the element itself. To extract gradient colors, select <stop> elements with QuerySelectorAll("stop[stop-color]") and read their stop-color attributes with
GetAttribute().
This example is intentionally narrower than the first one: it looks only at gradient stops. Use it when you need to audit gradient palettes separately from flat fills and strokes.
1using Aspose.Svg;
2using Aspose.Svg.Dom;
3using System;
4using System.Collections.Generic;
5using System.IO; 1// Extract colors from SVG linear and radial gradient stops in C#
2
3// Load the source SVG file
4using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "replace-svg-colors.svg")))
5{
6 SortedSet<string> gradientColors = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
7
8 // Select gradient stop elements that define stop-color values
9 foreach (Element stopElement in document.QuerySelectorAll("stop[stop-color]"))
10 {
11 string color = stopElement.GetAttribute("stop-color").Trim();
12
13 if (!string.IsNullOrWhiteSpace(color))
14 {
15 gradientColors.Add(color);
16 }
17 }
18
19 // Print the unique colors used in SVG gradient stops
20 foreach (string color in gradientColors)
21 {
22 Console.WriteLine(color);
23 }
24}Use this pattern when you need to audit gradients separately from flat fills and strokes.
Expected console output:
1bisque
2grey
3silverSVG colors can be written in different formats: named colors, HEX values, RGB values, HSL values, and more. If you need to compare colors reliably, normalize extracted color values with the Color class.
The
Color.FromString() method parses a CSS color string into a Color object. Then
ToRgbHexString() returns a consistent HEX representation that is easier to compare, store, or report.
1using Aspose.Svg.Drawing;
2using System;
3using System.Collections.Generic; 1// Normalize SVG color names, HEX values, and RGB values to HEX in C#
2
3List<string> sourceColors = new List<string>
4{
5 "red",
6 "#808080",
7 "rgb(128, 128, 128)"
8};
9
10// Convert each color value to HEX for easier comparison
11foreach (string sourceColor in sourceColors)
12{
13 Color color = Color.FromString(sourceColor);
14 Console.WriteLine($"{sourceColor} -> {color.ToRgbHexString()}");
15}Normalization helps you detect duplicates when the same visual color is written in different formats. For more color conversion examples, see Convert Color Codes.
Use normalization as a second step after extraction. The extraction examples above keep the original text values so you can see exactly how colors are written in the SVG source.
The final example combines attribute colors and inline style colors into one unique palette. It keeps paint server references out of the result and collects the direct color values used by the SVG.
This is the most practical workflow when you need one palette for reporting, validation, or a later replacement step. It combines the attribute scan and the inline style scan, while still skipping none, currentColor, and url(#id).
1using Aspose.Svg;
2using Aspose.Svg.Dom;
3using System;
4using System.Collections.Generic;
5using System.IO; 1// Build a unique SVG color palette from attributes and inline styles in C#
2
3using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "replace-svg-colors.svg")))
4{
5 string[] colorAttributes = { "fill", "stroke", "stop-color" };
6 HashSet<string> colorProperties = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
7 {
8 "fill",
9 "stroke",
10 "color",
11 "stop-color"
12 };
13
14 SortedSet<string> palette = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
15
16 // Collect direct color values from SVG presentation attributes
17 foreach (Element element in document.QuerySelectorAll("*"))
18 {
19 foreach (string attributeName in colorAttributes)
20 {
21 string value = element.GetAttribute(attributeName);
22
23 if (string.IsNullOrWhiteSpace(value))
24 {
25 continue;
26 }
27
28 string color = value.Trim();
29
30 if (!color.Equals("none", StringComparison.OrdinalIgnoreCase) &&
31 !color.Equals("currentColor", StringComparison.OrdinalIgnoreCase) &&
32 !color.StartsWith("url(", StringComparison.OrdinalIgnoreCase))
33 {
34 palette.Add(color);
35 }
36 }
37 }
38
39 // Collect direct color values from inline CSS declarations
40 foreach (Element element in document.QuerySelectorAll("[style]"))
41 {
42 string style = element.GetAttribute("style");
43
44 foreach (string declaration in style.Split(';', StringSplitOptions.RemoveEmptyEntries))
45 {
46 string[] parts = declaration.Split(':', 2);
47
48 if (parts.Length != 2)
49 {
50 continue;
51 }
52
53 string property = parts[0].Trim();
54 string value = parts[1].Trim();
55
56 if (colorProperties.Contains(property) &&
57 !value.Equals("none", StringComparison.OrdinalIgnoreCase) &&
58 !value.Equals("currentColor", StringComparison.OrdinalIgnoreCase) &&
59 !value.StartsWith("url(", StringComparison.OrdinalIgnoreCase))
60 {
61 palette.Add(value);
62 }
63 }
64 }
65
66 // Print the complete unique SVG color palette
67 foreach (string color in palette)
68 {
69 Console.WriteLine(color);
70 }
71}Use this combined workflow when you need a practical SVG color inventory before validation, reporting, or recoloring.
Expected console output for the sample file:
1bisque
2grey
3silver| Problem | Cause | Fix |
|---|---|---|
The palette contains url(#id) values | The scan collected paint server references from fill or stroke | Skip url(...) values and inspect gradient <stop> elements separately |
| The palette contains values that are not visible colors | The scan included paint keywords such as none or inherited values such as currentColor | Filter these values unless you intentionally audit SVG paint semantics |
| Gradient colors are missing from the report | Only shape attributes were inspected, while the actual colors are stored in <stop> elements | Query stop[stop-color] and read the stop-color attribute |
| Duplicate colors appear | The same visual color is written as a name, HEX, or RGB | Normalize values with Color.FromString() before comparing |
| Inline style colors are missing | Only SVG presentation attributes were inspected | Parse elements with the [style] selector and read color-related CSS declarations |
| CSS rule colors are missing | Colors are stored inside a <style> element or external stylesheet | Inspect CSS rules separately when your SVG uses stylesheet-based styling |
How do I extract all colors from an SVG file in C#?
Use SVGDocument to load the file, QuerySelectorAll("*") to inspect SVG elements, and GetAttribute() to read fill, stroke, and stop-color. Parse inline style attributes separately and collect unique values in a HashSet or SortedSet.
How do I get a unique SVG color palette in C#?
Collect colors from SVG attributes and inline styles, skip none, currentColor, and url(#id), then store the results in a case-insensitive SortedSet<string>. Normalize with Color.FromString() if equivalent values such as grey and #808080 should be treated as the same color.
How do I extract gradient colors from SVG?
Select gradient stop elements with QuerySelectorAll("stop[stop-color]") and read each stop-color value with GetAttribute(). A shape with fill="url(#id)" references a gradient and does not store the actual gradient colors itself.
How do I extract colors from inline SVG styles?
Select elements with QuerySelectorAll("[style]"), split the style attribute into CSS declarations, and read color-related properties such as fill, stroke, color, and stop-color.
Should none, currentColor, and url(#id) be included in an SVG color palette?
Usually no. none means no paint, currentColor is inherited from CSS, and url(#id) references a paint server such as a gradient. Skip them for a direct color palette, or keep them only for a full paint audit.
How do I normalize extracted SVG colors to HEX?
Use Color.FromString() to parse each extracted color string, then call ToRgbHexString() to output a consistent HEX value. This helps deduplicate colors written as names, HEX, or RGB values.
Can I use extracted SVG colors for recoloring?
Yes. Use the extracted palette as the source list for a replacement map, then update matching fill, stroke, stop-color, or inline style values. See
Replace SVG Colors in C# for the replacement workflow.
<stop> elements.Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.