Wednesday, December 1, 2010

Changing the opacity of an Image (.NET C#)

Setting up the opacity of an Image is very useful and reasonably easy to to. In my Card Maker application I needed to load a bitmap, set the opacity, and make sure the image file was not locked(!).

The critical piece is the configuration of the Matrix33 value. This configures the alpha component of the matrix. (a value from 0 to 1 in my sample)

It is important to call Dispose on loaded images files that are no longer needed. This is critical to avoid locking the file (and angering you and your application users).

ColorMatrix zColor = new ColorMatrix();
zColor.Matrix33 = (float)opacity / 255.0f;
ImageAttributes zAttrib = new ImageAttributes();
Bitmap zSourceImage = new Bitmap(sFile);
Bitmap zBitmap = new Bitmap(zSourceImage.Width, zSourceImage.Height); // target image
Graphics zGraphics = Graphics.FromImage(zBitmap);
// draw the source image into the destination with the desired opacity
zGraphics.DrawImage(zSourceImage, new Rectangle(0, 0, zBitmap.Width, zBitmap.Height), 
0, 0, zBitmap.Width, zBitmap.Height, GraphicsUnit.Pixel, zAttrib);