Color Filters – C# Code

In this article, you will learn about the main color filters – <feColorMatrix> and <feComponentTransfer>. Here you’ll find examples showing how to write SVG code to create saturation, hueRotate, and luminanceToAlpha effects, as well as detailed C# examples of using the Aspose.Svg.Filters namespace to apply color filters to SVG elements or bitmaps.

Color Filters

Aspose.SVG for .NET lets you create various SVG filter effects that are supported in almost all modern browsers. When it comes to color handling, <feColorMatrix> is the best option. It is a type of color filter that uses a matrix to affect the color values for each RGBA channel. The <feComponentTransfer> is one of the most powerful SVG filter primitives. It gives control over the individual RGBA channels of the image, allowing you to create Photoshop-like SVG effects; for example, it can be used to posterize images.

Color Matrix – <feColorMatrix> filter primitive

The <feColorMatrix> is one of the main color filters. This filter primitive applies a matrix transformation to the RGBA channels of each pixel in the input image. As a result, a new set of color and alpha values is produced. In the common case, the color matrix is written as an operation of the type attribute of the <feColorMatrix> element. In the special cases of color matrices, the auxiliary operations of the type are used: saturate, hueRotate, luminanceToAlpha.

Saturation Effect

The saturation effect is a special case of using the color matrix. Let’s see examples of the saturate operation used in the type attribute of the <feColorMatrix> filter primitive:

1<svg xmlns="http://www.w3.org/2000/svg">
2    <image filter="url(#saturation-effect)" href="http://docs.aspose.com/svg/net/images/api/lighthouse.jpg" x="20" y="20" height="440" width="330" />
3    <defs>
4        <filter id="saturation-effect">
5            <feColorMatrix in="SourceGraphic" type="saturate" values="2"></feColorMatrix>
6        </filter>
7    </defs>
8</svg>

The above SVG code illustrates the creation of the saturation effect and reminds you that in SVG, a filter is defined by a <filter> element that is set inside a <defs> element. It is never rendered itself and is conceptually described as an element that includes its child elements, the filter primitives.

The following C# code creates an SVG file with an image with increased saturation, making the colors appear more vibrant. The saturation effect is achieved by the <feColorMatrix> filter primitive with the values specified in the code.

 1using Aspose.Svg;
 2using System.IO;
 3using Aspose.Svg.Filters;
 4using Aspose.Svg.DataTypes;
 5...
 6
 7    // Set SVG Namespace Url
 8    string SvgNamespace = "http://www.w3.org/2000/svg";
 9
10    using (var document = new SVGDocument())
11    {
12        var svgElement = document.RootElement;
13
14        // Create an <image> element and add to the <svg> element
15        var imageElement = (SVGImageElement)document.CreateElementNS(SvgNamespace, "image");
16        imageElement.Href.BaseVal = "http://docs.aspose.com/svg/net/images/api/lighthouse.jpg";
17        imageElement.Height.BaseVal.ConvertToSpecifiedUnits(SVGLength.SVG_LENGTHTYPE_PX);
18        imageElement.Width.BaseVal.ConvertToSpecifiedUnits(SVGLength.SVG_LENGTHTYPE_PX);
19        imageElement.Height.BaseVal.Value = 440;
20        imageElement.Width.BaseVal.Value = 330;
21        imageElement.X.BaseVal.Value = 20;
22        imageElement.Y.BaseVal.Value = 20;
23        imageElement.SetAttribute("filter", "url(#saturation)");
24        svgElement.AppendChild(imageElement);
25
26        // Create a <defs> element and add to the <svg> element
27        var defsElement = (SVGDefsElement)document.CreateElementNS(SvgNamespace, "defs");
28        svgElement.AppendChild(defsElement);
29
30        // Creating a <filter> element and add to the <defs> element
31        var filterElement = (SVGFilterElement)document.CreateElementNS(SvgNamespace, "filter");
32        filterElement.Id = "saturation";
33        defsElement.AppendChild(filterElement);
34
35        // Creating a <feColorMatrix> element and add to the <filter> element
36        var feColorMatrixElement = (SVGFEColorMatrixElement)document.CreateElementNS(SvgNamespace, "feColorMatrix");
37        feColorMatrixElement.In1.BaseVal = "SourceGraphic";
38        feColorMatrixElement.SetAttribute("type", "saturate");
39        feColorMatrixElement.SetAttribute("values", "2");
40        filterElement.AppendChild(feColorMatrixElement);
41
42        // Save the document
43        document.Save(Path.Combine(OutputDir, "saturation-effect.svg"));
44    }

Let’s consider the code step by step:

  1. Create an instance of the SVGDocument class.
  2. The RootElement property of the SVGDocument class points to the document’s root <svg> element.
  3. Create an <image> element with attributes and add it to the <svg> element:
    • You can use the CreateElementNS(namespaceURI, QualifiedName) method to create an instance of the SVGImageElement class.
    • Set attributes specifying its source, position, and size. Using a filter attribute of imageElement referring to the url name of an id attribute in filterElement allows applying the SVG filter effect to the image.
    • To add an imageElement to svgElement, you can use the AppendChild() method.
  4. Create a <defs> element and add it to the <svg> element:
    • Use the CreateElementNS() method to create an instance of the SVGDefsElement class.
    • Use the AppendChild() method to add the <defs> element to the <svg> element.
  5. Create a <filter> element, set an id attribute, and add <filter> to the <defs> element:
    • Use the CreateElementNS() method to create an instance of the SVGFilterElement class.
    • Set a filterElement.Id for the <filter> element, it can be applied to the image.
    • Use the AppendChild() method to add the <filter> to the <defs> element.
  6. Create a <feColorMatrix> element, set attributes, and add it to the <filter> element:
    • Use the CreateElementNS() method to create an instance of the SVGFEColorMatrix class.
    • Call the SetAttribute(name, value) method to set type and value attributes.
    • Don’t forget to set in1 attribute. Use the property of the SVGAnimatedLength type, the static data for which can be set or read through the construction feColorMatrixElement.In1.BaseVal = "SourceGraphic".
    • Use the AppendChild() method to add the <feColorMatrix> to the <filter> element.
  7. Call the Save() method to save the SVG document with the saturated image to a local file specified by path.

HueRotate

The specific case of color matrices is image rotation along the color wheel. The type="hueRotate" operation is used to change the color tone of an image or element. With hueRotate, you can create vivid, rich color effects and customize the appearance of your website elements. The hueRotate takes a values – the rotation angle in degrees. This angle indicates the angle to rotate the color wheel. The value can be between 0 and 360, where 0 and 360 represent the original color tone, and 180 represents a 180-degree rotation (the colors are reversed).

The following SVG example illustrates using the type="hueRotate" operation in the <feColorMatrix> filter primitive:

1<defs>
2    <filter id="hueRotate">
3        <feColorMatrix in="SourceGraphic" type="hueRotate" values="150"></feColorMatrix>
4    </filter>
5</defs>

The C# code below creates a <feColorMatrix> filter primitive and adds it to an existing SVG <filter> element to apply a hueRotate effect using Aspose.SVG for .NET API. The hue rotation effect changes the hue of the input graphic, effectively shifting its colors around the color wheel.

1    // Creating a <feColorMatrix> element and add to the <filter> element
2    var feColorMatrixElement = (SVGFEColorMatrixElement)document.CreateElementNS(SvgNamespace, "feColorMatrix");
3    feColorMatrixElement.In1.BaseVal = "SourceGraphic";
4    feColorMatrixElement.SetAttribute("type", "hueRotate");
5    feColorMatrixElement.SetAttribute("values", "150");
6    filterElement.AppendChild(feColorMatrixElement);

This figure is a series of images with various type attribute values. The figure demonstrates the source image (a), the images processed by the feColorMatrix filter – after the saturation effect applying (b), hueRotate (c), and luminanceToAlpha (d).

Text “A series of images with various values of the color matrix type attribute – saturate, hueRotate, and luminanceToAlpha.”

Color Channels – <feComponentTransfer> filter primitive

The <feComponentTransfer> filter primitive is a powerful SVG element that allows you to perform linear, tabular, discrete operations with image channels and change the gamma of each channel (RGBA). This enables various color adjustments and effects such as contrast changes, gamma correction, color inversion, brightness adjustment, and more.

Usually sub-elements <feFuncR>, <feFuncG>, <feFuncB>, and <feFuncA> are used with <feComponentTransfer>. They define the transform functions for the red, green, blue, and alpha channels, respectively, and can contain attributes such as type, tableValues, slope, intercept, amplitude, exponent, and offset that define the behavior of the transform. In the type attribute, the type of function that allows modifying this component is determined. There are five function types: identity, table, discrete, linear, and gamma. When type="linear", the slope attribute indicates the slope of the linear function. If the attribute is not specified, then the effect is as if a value of 1 were specified. Let’s look at an SVG example:

 1<svg xmlns="http://www.w3.org/2000/svg">
 2	<image href="http://docs.aspose.com/svg/images/api/seaside.jpg" height="330" width="440" x="10" y="10" filter="url(#rgba)" />
 3    <defs>
 4		<filter id="rgba">
 5			<feComponentTransfer>
 6				<feFuncR type="linear" slope="1.1"/>
 7				<feFuncG type="linear" slope="1.5"/>
 8				<feFuncB type="linear" slope="2.0"/>
 9				<feFuncA type="identity"/>
10			</feComponentTransfer>
11		</filter>
12	</defs>
13</svg>

Here we will write C# code to create the same image channel linear transformation effect as in the above SVG code.

 1using Aspose.Svg;
 2using System.IO;
 3using Aspose.Svg.Filters;
 4...
 5
 6    // Set SVG Namespace Url
 7    string SvgNamespace = "http://www.w3.org/2000/svg";
 8
 9    using (var document = new SVGDocument())
10    {
11        var svgElement = document.RootElement;
12
13        // Create an <image> element and add to the <svg> element
14        var imageElement = (SVGImageElement)document.CreateElementNS(SvgNamespace, "image");
15        imageElement.Href.BaseVal = "http://docs.aspose.com/svg/images/api/seaside.jpg";
16        imageElement.Height.BaseVal.Value = 330;
17        imageElement.Width.BaseVal.Value = 440;
18        imageElement.X.BaseVal.Value = 10;
19        imageElement.Y.BaseVal.Value = 10;
20        imageElement.SetAttribute("filter", "url(#rgba)");
21        svgElement.AppendChild(imageElement);
22
23        // Create a <defs> element and add to the <svg> element
24        var defsElement = (SVGDefsElement)document.CreateElementNS(SvgNamespace, "defs");
25        svgElement.AppendChild(defsElement);
26
27        // Creating a <filter> element and add to the <defs> element
28        var filterElement = (SVGFilterElement)document.CreateElementNS(SvgNamespace, "filter");
29        filterElement.Id = "rgba";
30        defsElement.AppendChild(filterElement);
31
32        // Creating a <feComponentTransfer> element and add to the <filter> element
33        var feComponentTransferElement = (SVGFEComponentTransferElement)document.CreateElementNS(SvgNamespace, "feComponentTransfer");
34        filterElement.AppendChild(feComponentTransferElement);
35
36        // Creating a <feFuncR> element and add to the <feComponentTransfer> element
37        var feFuncRElement = (SVGFEFuncRElement)document.CreateElementNS(SvgNamespace, "feFuncR");
38        feFuncRElement.SetAttribute("type", "linear");
39        feFuncRElement.SetAttribute("slope", "1.1");
40        feComponentTransferElement.AppendChild(feFuncRElement);
41
42        // Creating a <feFuncG> element and add to the <feComponentTransfer> element
43        var feFuncGElement = (SVGFEFuncGElement)document.CreateElementNS(SvgNamespace, "feFuncG");
44        feFuncGElement.SetAttribute("type", "linear");
45        feFuncGElement.SetAttribute("slope", "1.5");
46        feComponentTransferElement.AppendChild(feFuncGElement);
47
48        // Creating a <feFuncB> element and add to the <feComponentTransfer> element
49        var feFuncBElement = (SVGFEFuncBElement)document.CreateElementNS(SvgNamespace, "feFuncB");
50        feFuncBElement.SetAttribute("type", "linear");
51        feFuncBElement.SetAttribute("slope", "2.0");
52        feComponentTransferElement.AppendChild(feFuncBElement);
53
54        // Creating a <feFuncA> element and add to the <feComponentTransfer> element
55        var feFuncAElement = (SVGFEFuncAElement)document.CreateElementNS(SvgNamespace, "feFuncA");
56        feFuncAElement.SetAttribute("type", "identity");
57        feComponentTransferElement.AppendChild(feFuncAElement);
58
59        // Save the document
60        document.Save(Path.Combine(OutputDir, "rgba.svg"));
61    }

The figure demonstrates the source image (a) and the images processed by the feComponentTransfer filter (b, c).

Text “The result of the feComponentTransfer filter applying”

See also

  • You can download the complete examples and data files from GitHub.

  • About downloading from GitHub and running examples, you find out from the How to Run the Examples section.

  • For more information about filter primitives, see the W3C Filter Effects Module page and the SVG Filters and Gradients article.

  • Aspose.SVG offers free SVG Web Applications for converting SVG or image files, merging SVGs, image vectorizing, SVG sprite generating, SVG to Base64 data encoding, and more. These online applications work on any operating system with a web browser and don’t require additional software installation. It’s a fast and easy way to efficiently and effectively solve your SVG-related tasks!

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.