GDI+ FAQ: Create a negative
image.
The simple task of
inverting the colours in an image can be accomplished using the ColorMatrix class.
The steps to perform
are as follows:
- Open the original image from
disc
- Create an image in memory the same size as
the original.
- Create an inverting matrix and attach it to
an ImageAttributes object.
- Get a Graphics object for the
image.
- Draw the original image to the copy using
the ColorMatrix to invert the colours.
The C# code for this
process is shown in the following listing.
Image
img=Image.FromFile(<filename>);
Bitmap
copy=new
Bitmap(img.Width,img.Height);
ImageAttributes
ia = new
ImageAttributes();
ColorMatrix
cm=new
ColorMatrix();
cm.Matrix00=
cm.Matrix11=
cm.Matrix22=-1;
ia.SetColorMatrix(cm);
Graphics
g=Graphics.FromImage(copy);
g.DrawImage(img,new Rectangle(0, 0, img.Width, img.Height), 0,
0, img.Width, img.Height, GraphicsUnit.Pixel, ia);
g.Dispose();
img.Dispose();
Note how the
ColorMatrix properties are set so that the elements at 0,0 1,1 and 2,2 are
set to -1. Setting the matrix element at 3,3 will invert the Alpha of the
image also and may make it fully transparent.
Back to the GDI+
FAQ
|