Introduction

I decided to write these tutorials after I realized that I didn’t really
understand how C# handled transparency. I was doing some alpha blending and the
resulting colors were not what I expected. So I built a tool, AlphaBlender
Figure 1, to show a Venn diagram of the colors mixed like in standard color
theory texts and I was further puzzled that the tool produced an image unlike
any I’d seen in school.

Figure 1 AlphaBlender demo application

Figure 2 shows what I got versus what I expected.

Figure2, Alpha blend versus my expectations of ‘real’ blended colors

Well… nobody told me that alpha blending was supposed to be like my
expectations; in fact, I am frequently surprised at how little anything works
like I first expect it too. So I decided to write these tutorials to help me
understand what’s really going on with transparency in C#.

In each of these tutorials, we consider the ‘what’ before the ‘how’-- a
discussion is presented of the concepts behind the code, and then at the end, we
look at the code behind the concepts. In the code section, I’ll introduce each
relevant new element of GDI+ as it occurs, and I won’t mention it again if it
reoccurs in later code. This should help with redundancy and get the elementary
stuff over with quickly.

Also a word of caution: I’m no C# guru. I’ve written the demonstration code
to illustrate the transparency concepts, not to demonstrate good programming
practice. I encourage any and all to send me comments on my coding practices and
how I might improve them.

The Concepts

What Is Color?

Color is a human thing. It is defined by our ability to perceive a narrow
band of the electromagnetic spectrum that we call visible light. Our eyes have
’rod’ cells that sense variations in black and white, and we have three types of
cone cells, one each for red, green and blue.

We can simulate our perception of color by mixing red, green, and blue, which
is what a computer monitor does. This brings us to the natural use of these
components to create colors in C#, where a color is a 32-bit structure of four
bytes for Alpha, Red, Green, and Blue

Alpha is a transparency parameter that defines how much of the existing
display color pixel that should ‘show through’ the new color.

Visualization Tools

I propose that if a picture is worth a thousand words, then a demo program is
worth a ten thousand. The following demonstrations show some things about
transparency use in C#.

I wrote ColorMaker, Figure 3, to show the effect of varying each of the color
structure parameters. The color is created over a gradient, black to white, to
illustrate how the Alpha value affects the ‘show through’ of the background
color

Figure 3, ColorMaker demo application

Next I wrote WhatColorIsIt, Figure 4, to show the color parameters for any
pixel on the screen. (This demo is based on Charles Petzold’s WhatColor example
from his C# book).

Figure 4, WhatColorIsIt demo application

I combined what I learned with these two programs and wrote Spectrum, Figure
5, which simulates the color spectrum of visible light and allows the user to
read the color parameters.

Figure 5 Light spectrum simulation demo application

Transparency

I started this tutorial because I didn’t understand how alpha blending
actually worked. Figure 1 shows what I was getting versus what I was expecting,
and it also shows fairly obviously what is really going on. Alpha blending does
not work like blending light; it works like stacking glass filters.

If you take a red, green, and blue glass filters and lay them on a
background, you would get an effect like what we see in the demo. Filters with
50% transparency should look like the demo with alpha set to 127.

I wrote a tool, Alpha Demonstrator Figure 6, to show the effect of ‘stacking’
order and background color to further illustrate what’s really going on. You can
change the stacking order and background color in the demo to view each stacking
and background color permutation.

Figure 6, Alpha Demonstrator

To wind things up for this tutorial, I wrote Color Demo, Figure 7, which
shows additive and subtractive color and effects of various backgrounds, the way
I think they should look to simulate the ‘real’ world.

protectedoverridevoid OnPaint(System.Windows.Forms.PaintEventArgs e)
{
// Fill in Background (for efficiency only the area that has been clipped)
e.Graphics.FillRectangle(new SolidBrush(SystemColors.Window),
e.ClipRectangle.X,
e.ClipRectangle.Y,
e.ClipRectangle.Width,
e.ClipRectangle.Height);
//// Do your drawing
////// Make darn sure you dispose of everything that you create
// that is disposable (brushs, pens, bitmaps, etc.). Garbage
// collection will get rid of the stuff eventually, but it is
// real easy to overload the system with lots of paints.
//}

Color Maker

The ColorMaker, Figure 3, allows the user to use slider controls to set the
red, green, blue, and alpha parameters of the color structure and paint the
results over a black to white gradient background.

This is hardly a beginner topic, but I’ve included it here because the tool
itself is so useful and it gives quick insight in how to expand your C# toolset.
Make certain that you dispose of anything you create from a DLL since it is
unmanaged and doesn’t get garbage collected when you close.

LightSpectrum

To the concepts we’ve looked at so far, LightSpectrum, Figure 5, elaborates
on the gradient brush to simulate a full spectrum of visible light. I reuse this
code in several subsequent demonstrations, so in a real-world coding situation
(this is an unreal-world) I’d put this stuff in its own class. This, as is,
really has nothing to do with transparency, but I use it later as a backcolor
for transparency demos.

In the OnPaint method we add a new LinearGradientBrush
with some dummy colors.

AlphaDemonstrator

I built AlphaDemonstrator, Figure 6, to show more variations on alpha
blending as it actually works and contrary to my expectations. No new code
concepts are added, so no extra discussion is given.

ColorDemo

I wrote ColoDemo to provide a simulation of how I thought color and
transparency should be simulated for the ‘real world’. That is, what do we need
to do to get the effect of mixing paints or projecting colored lights?

This function receives the background bitmap1, the source bitmap2, the source
X and Y locations and alpha for the blend. It iterates through each pixel of
bitmap2 that overlays bitmap1, adds each pixel together, limiting the maximum
value to 255, then resets the bitmap1 pixel to the new red, green, and blue
values and sets alpha to the given alpha.

This provides a good simulation of additive color over a black background.

But it doesn’t work over white since, for white, bitmap1 starts out with all
color values already at 255. Putting color over white, subtractive color, is
what printers do, using Cyan, Magenta and Yellow as their primary colors. They
also use black, since they can’t get a good black mixing the colors, calling
their system CYMK, where K is the black. In the Color Demo code, all that’s
needed to demo subtractive color is to start with a white background and
subtract the pixels in bitmap2.

In the next tutorial, we’ll begin with images by looking at the
CompositingMode Enumeration and the ColorMatrix, and ImageAttributes
classes for making color changes to entire images.

Great article, very interesting concepts! I really would like to learn more about the subtractive and additive model...
I tried and downloaded the source projects, but I couldn't find the color demo project source for additive and subtractive to download and try.
Did you remove it? You can put the source code again?

But i will work in windows application only, is not working in wince application because creating the color object using "Color.FromArgb(int, int, int , int); " method. But it won't supported in wince .

Great article, very interesting concepts.
I tried and downloaded the source projects, but I couldn't find the color demo project source for additive and subtractive to download and try.
Did you remove it?
Thanks

When I wrote these articles, I didn't fully understand that mixing RGB doesn't actually produce a smooth spectrum in that yellow is produced from green and red, but since green has 256 values and red has 256 values then pure red or green don't appear as bright as yellow which is a mix of the two and can have 512 values. You can see this effect on the spectrum I generated which seem brighter in the three 'mixed' color bands: Cyan, Magenta, and Yellow. For this to produce a true spectrum in a physics sense the sum of the power being delivered to the red, the green, and the blue phosphors would have to be held constant and couldn't be greater than 256 total. That, of course assumes that the power out from each phosphor is same when stimulated with the same numeric value, an assumption I'm not sure we can make. If the output powers are the same, this would give as close a physics approximation as we could get. And the spectrum wouldn't look right because our eyes don't have linear sensitivity to spectral power. It is more complex than I thought and some day, I hope to revise these articles and get a more accurate picture of color reproduction.

I want to put some images in the menus and in the toolbar of an application.

For the image borders to apear smooth I have to use antialiasing and to save the image in a format that suports alpha transparency too, like png, not only index transparency like gif.

But when I import the image into the Visual c# it looses alpha transparency or something...

The fact is that, if i change the color scheme in windows and the color of the windows is chaged, my images from the menu and the toolbar apear with a rough margin beacouse only the index transparency is rendered.

Can somebody help me? (notice that i'm not a programmer, i'm only a graphics designer )

Sorry, I don't know how to address this specific problem. Menus and toolbars have specific properties that are not precisely like the base window where most of this tutorial was done, so they don't necessarily do the same thing in response to the transparency and color coding that happens on a window.

I think you were confused about the usage of the word 'blending' in alpha blending.

As you figured out the alpha blending does not mean color blending, instead it means real world transparency blending.

ex: Let's say I have two glasses (for drinking) one red and one blue. When I line them up and look through both of them, I am certainly not going to see some yellow!!!!!! Instead, I see a color blend very similar to the result of the c# alpha blend.

I have one simple program that can seperates one color picture into C,M,Y,K color layers (4 images). Now I want to combine these pictures back into one color picture (like origon one) under C#, How can I do that? I don't know how to do this combination process, could you help ??

I need more information. What is the program that does the initial separation? Did you write it or have the source code or any data on how it does the separation?

A little background: CMYK is used in printing where Cyan, Magenta, and Yellow subtract color from the white of the page. Printing inks combine to make a lousy black, so the K is pure black to give images and text crispness. I'm not an expert in this area, but I suspect that a lot of the algorithms for converting a RGB additive image suitable for a computer moniter to a CYMK image suitable for a printer are subjectivly and empirically derived and depends on the monitor and printer. I'm still guessing, but the best bet for your conversion is to get the original algorithm and run it backward. Likely though you don't have access to the origial algorithm.

So, more questions:

What is the format of the image you want to convert? How do you get it into a C# program?
What was the format of the original image?

Generally, provide more detail to the question and maybe I can give some hints that will get you going in the right direction.

For the seperation demo program, it is not written by me, it is one kind of printing software which my supervisor get it from somewhere. It can seperates picture into C,M,Y,K (like Tiff, bmp etc), seperated picture is bmp/jpg format.

In my project, my supervisor hopes me to make it possible to preview the picture in color view or seperated view at anytime. So I get these seperated pictures and going to preview them as origion color picture.

In C# I can preview each of them, just using new Bitmap(), but don't know how to combine & preview them like original one. So I just ask for you, if you have done this kind of function.

I am slowly trying to put together a color tutorial which includes simple methods for calibrating monitors, printers, scanners, and digital cameras, but it is turning out to be more complex than I hoped, so it will take a while to complete.

I googled "color space faq tutorial" and got some leads for you. Much of what I saw leads me to believe that CMYK -> RGB is done with two simple algorithms first to convert CMYK to CMY then to convert CMY to RGB, but some of what I've read leads me to believe that a lot of esoteric tweaking must be done to get really useful results. Apparently PhotoShop has some good proprietary algorithms that work fine but they won't share them.

Thanks for the advice. I was learning while doing and didn't figure out enough about COM interop and unsafe programming to do what you suggest until the third tutorial, but since this is the first and it is for beginners, I think the code fragment is probably clearer as is, though definately sloooow...

I coded such a method, in order to optimise and to avoid using GetPixel and SetPixel. The code can be downloaded from www.inf.ufrgs.br/~rrferreira/inf01046/SourceCodeTwo.zip. Just take a look inside the JPEG class that I implemented. I was based on a previous MSDN article. The time required to perform some simple image transforms are dramastically reduced by coding with unmanaged code (the order is about 28 times faster than managed code).

Colour is a very strange thing, additional colour mixing, subtractive colour mixing and the fact that there are different primary colours for light and for pigment. if you are a 'paint' artist , you can't make white but you can with lights. (and obviously you can make what ever colours you like on screen.)
I really like this app. it demonstrates a lot.

Not really. I've shown a demo at the end that does subractive color. As I say in the article, alpha blending acts like stacking glass filters. Compare the alpha blend demo to the additive/subtractive demo to see what I mean.

This shows the blocks overlapping and displayed non overlapped. They grade like I expected. The alpha blending algorithm does not change the alpha value of the results, but it may cause the colors components to increase in value. This is not opacity, which is the inverse of transparency and is a measure of how much of the background shows through, as does alpha.