![]() |
Welcome to Dennis Lang's Source Code and Performance Metrics
lang.dennis@comcast.net Updated: 7-Apr-2010 |
![]() |
colormatrix C# source code and executables (xp32/net3.5): |
This C# application demonstrates the effect of using the ColorMatrix operator on an image. This program contains several sample matrix filters which you can select and modify. The top portion of the program interface contains three images. A background image, an overlay and the result of applying the color matrix on the overlay rendered on top of the background image. Each of the three panels display their image over a checkerboard background to make it easier to see partial transparent areas (alpha < 255). The bottom section of the interface shows the active color matrix filter on the left and a gallery of pre-built filters on the right.
Here is a code fragment which shows how you can call DrawImage with a ColorMatrix.Color Matrix Features:
Three quick image load buttons for the background and overlay image Load user images into backgroud or overlay Save final image Edit color matrix Select one or more matrix cells and use slider bar to modify selections and see results Save and Load color matrix with image. Select from sample filters Load additional sample filters. Spinning "about" dialog on open and close (eye candy) Other Feaures:
Embedded html help with images Spinning "about" dialog when it opens and closes Custom window frame Embedded zip of ColorMatrix filter samples
float[][] dataArray; // fill with filter values... float gamma = 1.0f; // no change in gamma ImageAttributes imageAttributes = new ImageAttributes(); imageAttributes.ClearColorMatrix(); imageAttributes.SetColorMatrix(new ColorMatrix(dataArray), ColorMatrixFlag.Default, ColorAdjustType.Bitmap); imageAttributes.SetGamma(gamma, ColorAdjustType.Bitmap); Rectangle rect = new Rectangle(Point.Empty, image.Size); g.DrawImage(image, rect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, imageAttributes);
As an image is rendered using the color matrix, each pixel color channel (Red, Green, Blue, Alpha) is transformed by the color matrix. The color matrix transformation executes several math operations on the pixel color.
Before appling the matrix, the input source color channels are scaled from their native range of 0..255 to a range of 0.0 to 1.0. After applying the matrix transformation, the value is scaled by 255 to return it to its natural range, clamping it between 0 and 255. The upper left 4x4 zone of the matrix is multipled against the color's 4 channels (Red, Green, Blue, Alpha). The right column of the matrix is not used. The bottom row of the matrix is used as an offset to shift the color. The color matrix can have negative numbers and numbers greater than 1. It is easier to follow the math by looking at the samples below and there are other good explanations on the web, see reference links at the bottom of this article.out(r,g,b,a) = (in(r,g,b,a)/255 * matrix_scale + matrix_offset) * 255
The color matrix is applied to every pixel in the image as it is drawn into the graphics buffer. The following figure shows how a single source pixel is converted to a single destination pixel. Futher down I show specific sample matrix filters.
Source | Matrix | Destination | |||||||||||||||||||||||||||||||||||
| * |
| = |
|
Rd = (Rr * Rs) + (Rg + Gs) + (Rb * Bs) + (Ra * As) + Ro
Gd = (Gr * Rs) + (Gg + Gs) + (Gb * Bs) + (Ga * As) + Bo
Bd = (Br * Rs) + (Bg + Gs) + (Bb * Bs) + (Ba * As) + Go
Ad = (Ar * Rs) + (Ag + Gs) + (Ab * Bs) + (Aa * As) + Ao
If you change cells, press the Apply button to apply the new matrix to the overlay image. If you use the slider bar, it will automatically apply the changes.
In all of these examples, the color matrix is only applied to the 2nd image (overlay). The first image is the background, second is the overlay, and third is the result of drawing the overlay with the color matrix over the background image.
The 4 numbers under the source column is a sample Red,Green,Blue,Alpha pixel value. The 4 numbers under the destination column is the result of applying the matrix to the sample source pixel.
Source | Matrix | Destination | |||||||||||||||||||||||||||||||||||||||||||||||
| * |
| = |
|
|
Source | Matrix | Destination | ||||||||||||||||||||||||||||||||||||||||||||||
| * |
| = |
|
|
Source | Matrix | Destination | ||||||||||||||||||||||||||||||||||||||||||||||
| * |
| = |
|
|
destColor = overlayColor * alphaPercent + backgroundColr * (100% - alphaPercent)Example with Alpha=60%:
An overlay color(10,20,30) blended at 60% on top of a gray color(20,20,20) becomes (14,20,26)
Overlay Background Equation Result Red 10 20 10*0.6 + 20*0.4 14 Green 20 20 20*0.6 + 20*0.4 20 Blue 30 20 30*0.6 + 20*0.4 26
Source | Matrix | Destination | ||||||||||||||||||||||||||||||||||||||||||||||
| * |
| = |
|
|
(Red * 1 + Blue * 1 + Green * 1) -0.5 * 256 = destination_color_channel
100 + 20 + 30 - 128 = 22
Source | Matrix | Destination | ||||||||||||||||||||||||||||||||||||||||||||||
| * |
| = |
|
|
How do I embedded and view a HTML file which contains images?The answer is two part:
// Attach the embedded html resource Assembly a = Assembly.GetExecutingAssembly(); Stream htmlStream = a.GetManifestResourceStream("ColorMatrix_ns.colormatrix.html"); this.webBrowser.DocumentStream = htmlStream;
To produce the embedded html file used by ColorMatrix, I downloaded a base64 encoder and convert all of my images. There are tons of base64 utilities on the web. I used the following one: http://www.f2ko.de/English/b64/index.php I than search and replaced all of the original image tags which looked something like:<img src="data:image/jpg;base64,......." alt="image.jpg" />
With the following, where the ...... is the base64 image text.<img src="image.jpg" alt="image.jpg" />
I don't know how important it is to include the /jpg or what every type your original image is.<img src="data:image/jpg;base64,......." alt="image.jpg" />
<img src="data:image/jpg;base64,......." alt="image.jpg" />
The reason I says this, is I often used the wrong type for my encoded images and the image still displayed.
The base64 image is a text file which you can open with your favorite text editor and paste into your html file. Here is a sample of a few lines of a base64 encoded image:
2VDDoOw/Kuk8N2zqVncbUHTPU1zXh+y+0TZIG1ecGu1jbyolTOSOpFTgadTHVVia/TY48ZKnhIOh S6l9pqheb3qo83vUTTV9CeKeiNNULze9VGm96haagC281cL8RrL+0LeLzEV4cFWBGea6l5veqlwE mjZJBlGGCKAPCD4UtoZCYowvsK4L4zWyafa6DEgw8pnZvw2AV9IX3h5JCTBNt9mH9a+df2hoJLXX dItZCG8uNyCOhBI/wqJbo3pWcZ37fqjy+2UmQ4qWMsrOKm06ImbHrVt7M+Y5AqzAyRK/lsM9DVhL uRI4zk8VLFZkhxipGsW+y9OlAHf/AA68u6sVmkbJW5miK+zpEc/+Q67LSUuGlZJ9oAbAKg1wvwrtThe base64 can be spread across multiple lines, as in the example above. The exception is if you add a base64 encoded image to a style sheet. Inside a style sheet you must remove the line breaks in your base64 image and produce a single super long line.
For more exmples look at the colormatrix.html file which is part of the Visual Studio project for this program.
The code to implement the animation does the following:
Here is the code which grabs an image of the dialog being animated:
public Bitmap MakeScreenImage() { Bitmap image = new Bitmap(this.Width, this.Height); this.DrawToBitmap(image, new Rectangle(Point.Empty, image.Size)); image.MakeTransparent(this.TransparencyKey); return image; }
Here is the code to rotate the image capture using the code above:
See the rest of the details in about.cs code in the ColorMatrix project.private Bitmap rotateImage(Bitmap b, Size size, float angle, float scale, Image prevImage) { // Create a new empty bitmap to hold rotated image Bitmap returnBitmap; if (prevImage == null) returnBitmap = new Bitmap(size.Width, size.Height); else returnBitmap = new Bitmap(prevImage, size.Width, size.Height); // Make a graphics object from the empty bitmap Graphics g = Graphics.FromImage(returnBitmap); if (prevImage == null) g.Clear(Color.Transparent); g.SmoothingMode = SmoothingMode.HighSpeed; Size deltaSize = size - b.Size; g.TranslateTransform((float)deltaSize.Width / 2, (float)deltaSize.Height / 2); // Move rotation point to center of image g.TranslateTransform((float)b.Width / 2, (float)b.Height / 2); // Rotate g.RotateTransform(angle); // Move origin back g.TranslateTransform(-(float)b.Width / 2, -(float)b.Height / 2); // Draw passed in image onto graphics object g.ScaleTransform(scale, scale); g.DrawImage(b, new Point(0, 0)); return returnBitmap; }
Next I create a tableLayout object with 3 columns and 3 rows.
The rest of the work is to attach panels to the four edges and four corner zones of the table layout. Each panel gets an image and optionally you can attach mouse enter, leave and move handlers to support resizing or moving the dialog. You place all of your user interface components on a panel attached to the center zone. See MainForms.cs for examples of the mouse handlers.
private void saveFiltersBtn_Click(object sender, EventArgs e) { if (saveFilterDialog.ShowDialog() == DialogResult.OK) { Stream fileStream = File.OpenWrite(saveFilterDialog.FileName); GZipStream compressStream = new GZipStream(fileStream, CompressionMode.Compress, false); BinaryFormatter bFormatter = new BinaryFormatter(); foreach (Control control in filterFlow.Controls) { FilterGrid fg = (FilterGrid)control; bFormatter.Serialize(compressStream, fg.Label); bFormatter.Serialize(compressStream, fg.Source); bFormatter.Serialize(compressStream, fg.Image); } compressStream.Close(); } } private void LoadCompressedFiltersBtn_Click(object sender, EventArgs e) { if (loadFilterDialog.ShowDialog() == DialogResult.OK) { Stream fileStream = File.OpenRead(loadFilterDialog.FileName); LoadCompressedFilters(fileStream); } }