Color Transformation in C# GDI+ Programming

In this article, we will introduce GDI+, focus on basic color transformation programming with GDI+ in C#, and discuss the 4x4 and 5x5 color transformation matrix. We will then offer sample applications to demonstrate how to change existing color components.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 2
July 16, 2008
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

Overview of GDI+

GDI+ is the portion of the Windows XP or Windows Server 2003 operating system that provides two-dimensional vector graphics, imaging, and typography. GDI+ improves on the traditional Windows Graphics Device Interface (GDI) by adding new features and by optimizing existing features.

Because it's still a graphics device interface, GDI+ allows programmers to write device-independent applications. As with GDI, GDI+ allows developers to render data on a screen or printer without considering the details of a particular display device. The programmer makes calls to methods provided by GDI+ classes and those methods in turn make the appropriate calls to specific device drivers. GDI+ insulates the application from the graphics hardware, and it is this insulation that allows developers to create device-independent applications.

Let’s take a closer look at the position of GDI+ inside the whole .NET architecture.


Figure 1—GDI+ inside the whole system architecture

As is indicated in Figure 1, GDI+ is one of the modes to develop graphics applications along with GDI and DirectX. As higher wrapper classes, GDI+, like GDI, mainly serves to render graphics, images, and text with more powerful functionalities. Another important difference is that GDI+ adopts a new stateless pattern. This substitutes for GDI, which selects objects into a device context object (i.e. drawing operations within GDI+ are independent of each other).

On the other hand, the services of Microsoft Windows GDI+ can be divided into three categories: 2-D vector graphics, Imaging, and Typography.

2-D vector graphics involves drawing primitives (e.g. lines, curves, and figures) that are specified by sets of points on a coordinate system.

Because certain kinds of pictures are difficult or even impossible to display via vector graphics, various bitmaps are introduced to store various complex images. This is called Imaging. As you image, data structures that store information about bitmaps tend to be more complex than those required for vector graphics, so there are several classes in GDI+ devoted to this method.

Typography is concerned with the display of text in a variety of fonts, sizes, and styles. One of the new features in GDI+ is sub pixel anti-aliasing, which gives text rendered on an LCD screen a smoother appearance.

Introduction to Color Transformation

Tostoreand manipulateimages,GDI+ provides the Image and Bitmap classes, both of whichstore the color of each pixel as a 32-bit number: 8 bits each for red, green, blue, and alpha.Each of the four components is a number from 0 through 255, with 0 representing no intensity and 255 representing full intensity. The alpha component specifies the transparency of the color; 0 is fully transparent and 255 is fully opaque.

Author’s Note: transparency is one of the attractive characteristics of GDI+, which in some degree increases the complexity of color computation.

Therefore,a colorcan be described asa 4-dimensional vector(red, green, blue, alpha).For example, the color vector (255,0, 0, 255) represents acompleteopaque color that has nogreenor blue, but hasredat full intensity. This means that we can use a4×4colortransformationmatrix(see Figure 2) to modify any one of the four elements.


Figure 2—use a4 ×4colortransformationmatrixto change an element of a color

For example, to change color (0, 255, 0, 255) into semitransparent, we can replace the value of Alpha with 50% of its initial value. Figure 3 shows the related calculation.


Figure 3—change color (0, 255, 0, 255) into semitransparent

Wecan apply linear transformations (rotation, scaling, and the like) to color vectors by multiplying by a 4×4 matrix.However,wecannot use a 4×4 matrix to perform a nonlinear transformation, such astranslation.For this, we can introducea 5×5 matrix in order to apply any combination of linear transformations and translationssimultaneously by simply addinga dummy fifth coordinate to each of the color vectors.A transformation consisting of a linear transformation followed by a translation is called an affine transformation.A 5 ×5 matrix that represents an affine transformation is called a homogeneous matrix for a 4-space transformation. The element in the fifth row and fifth column of a 5 ×5 homogeneous matrix must be 1. All of the other entries in the fifth column must be 0.

For example, supposewewant to start with the color (25,100,100,255) andachievethe followingoperations.

  1. Double the red component

  2. Add 100 to the green component

We cannot achieve the two targets by just using 4x4 matrix multiplications. We have to resort to the above 5x5matrix that represents an affine transformation. The following Figure 4 shows how to perform the pair of transformations in the order listed.

Figure 4—performan affine transformationby adding a dummy coordinate

The above matrix calculation indicates that it’s necessary to use 5x5 matrixes to perform a color transformation.

However, before delving into the color transformation matrix, let’s introduce another important concept—color component saturation. If the value of the red component of a pixel is A, then the value of A/255 is called the red color component saturation.

GDI+ uses the color component saturation to represent the value of a color component in a pixel. For example, if the RGBA value of a pixel is (0, 255, 0, 255), then in terms of the color component saturation, the related representation is (0, 1, 0, 1). In other words, to change the value of a color component is to alter the color component saturation.

Now let’s examine what the color transformation matrix is.

In fact, a color transformation matrix is a kind of method to calculate the color component saturation. By default, a color transformation matrix can be defined as shown in Figure 5.


Figure 5—use identity matrix to define a default color transformation matrix

According to the definition of matrix calculation, any 1x5 vector multiplied by the above 5x5 identify matrix will keep the initial value. However, to alter the value in the main diagonal corresponds to performing multiplication with RGB components, while modifying other values relates to performing addition or subtraction with the RGB component saturation.

In GDI+, it’s through the function SetColorMatrix() of the ImageAttributes object that we achieve the alteration to a color transformation matrix. The following snippet lists several outlined signatures of the SetColorMatrix() function:

ImageAttributes.SetColorMatrix (ColorMatrix newColorMatrix);

ImageAttributes.SetColorMatrix (ColorMatrix newColorMatrix, ColorMatrixFlag mode);

ImageAttributes.SetColorMatrix (ColorMatrix newColorMatrix, ColorMatrixFlag mode, ColorAdjustType type);

For a more detailed explanation of the parameters used in the SetColorMatrix() function and a discussion of matrices and transformations, please refer to coordinate systems and transformations in MSDN. Now let's start to write a sample that uses color transformation matrices to change the color components.

A Sample that Uses Color Transformation Matrices

The following example takes an image of ASTRO BOY, who is the dramatis personae in the famous Japanese film ASTRO BOY. We are to apply the color transformation matrix described in the preceding paragraphs to accomplish the following result:

  1. Double the red component

  2. Set the color saturation of the red component to 1

When you launch the sample application, you will get the screenshot shown in Figure 6.

Figure 6—the running time snapshot of the sample application


The image shown on the left of Figure 6 corresponds to the original image, while the right one relates to the transformed image.

Now, let’s take a thorough look at the related source code.

Graphics graphics = this.CreateGraphics();

//use white color to populate the background

graphics.Clear(Color.White);


//load the original picture

Bitmap image = new Bitmap("ASTROBOY.bmp");

int width = image.Width;

int height = image.Height;

//create an instance of class ImageAttributes

ImageAttributes imageAttributes = new ImageAttributes();


//define the color transformation matrix

float[][] colorMatrixElements =

{

new float[]{2.0f, 0.0f, 0.0f, 0.0f, 0.0f},

new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f},

new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f},

new float[]{0.0f, 0.0f, 0.0f, 1.0f, 0.0f},

new float[]{1.0f, 0.0f, 0.0f, 0.0f, 1.0f}

};

ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);


//enable the color transformation matrix

imageAttributes.SetColorMatrix(

colorMatrix,

ColorMatrixFlag.Default,

ColorAdjustType.Bitmap);


//first render the source image

//at the specified location (0, 0)

graphics.DrawImage(image, 0, 0);

//next render the target image using the

//color transformation matrix defined above

graphics.TranslateTransform(width + 10, 0);

graphics.DrawImage(

image,

new Rectangle(0, 0, width, height),

0, 0,

width, height, GraphicsUnit.Pixel,

imageAttributes);

On the whole, the code in the preceding example utilizes the following steps to render the target image:

  1. Initialize a ColorMatrix structure.

  2. Create an ImageAttributes object and pass the address of the ColorMatrix structure to the SetColorMatrix() method of the ImageAttributes object.

  3. Pass the address of the ImageAttributes object to the Graphics::DrawImage() method of a Graphics object.

To present a more striking contrast to the previous sample, let’s check out another image (see Figure 7) that resembles the color matrix used in Adobe Photoshop.

Figure 7—the color matrix image comparison

That’s all for this simple sample.

Conclusion

In this article, we briefly introduced GDI+ and took a bird’s eye view of the whole GDI+ architecture. As a more flexible and powerful graphics device interface, GDI+ allows programmers to write more feasible device-independent graphic applications.

Next, we focused on discussing the newly-introducedcolor transformation matrix in GDI+ and became aware that the 5x5 color transformation matrix is practically the center of the whole color related computation.

Then, to gain a better understanding of thecolor transformation theory, we constructed a simple and typical sample application that uses the colortransformation matrix to change the color components in relation to the scenario's requirement.

Last but not least, whether from the point of view of traditional desktop application development or of the newly-prospering web application programming, it’s necessary for us to research into GDI+ in order to construct more professional, attractive applications.

In the remaining articles of this series we’ll delve even more into the color calculations in GDI+. We'll look at things like translating transformation, scaling transformation, rotating transformation, and shearing transformation.

-DOWNLOAD SOURCE-

blog comments powered by Disqus
C# ARTICLES

- Beginning C#
- ASP.NET RedirectPermanent Method using C# an...
- C Programming Language and UNIX Pioneer Pass...
- Using Facebook JavaScript SDK in ASP.NET wit...
- ASP.NET Export to Excel and Word using VB.NE...
- WAV and MP3 Streaming with ASP.Net and C#
- Game Programming using SDL: the File I/O API
- C# and Java Developer Jobs on the Rise
- The Future Evolution of C# and VB.NET
- C# If and Else-if Statements
- How To Use the C# String Replace Method
- 5 Ways to Parse XML in C#
- C# Meets Design Patterns
- Coding a CRC-Generating Algorithm in C
- Cyclic Redundancy Check

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 6 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials