A good way to do these relatively simple manipulations with images is to directly obtain the bitmap data yourself. Bob Powell wrote an article about this at http://www.bobpowell.net/lockingbits.htm . It explains how to block a bitmap and access its data through the marshal's class.
It is good to have a structure along these lines:
[StructLayout(LayoutKind.Explicit)] public struct Pixel { // These fields provide access to the individual // components (A, R, G, and B), or the data as // a whole in the form of a 32-bit integer // (signed or unsigned). Raw fields are used // instead of properties for performance considerations. [FieldOffset(0)] public int Int32; [FieldOffset(0)] public uint UInt32; [FieldOffset(0)] public byte Blue; [FieldOffset(1)] public byte Green; [FieldOffset(2)] public byte Red; [FieldOffset(3)] public byte Alpha; // Converts this object to/from a System.Drawing.Color object. public Color Color { get { return Color.FromArgb(Int32); } set { Int32 = Color.ToArgb(); } } }
Just create a new Pixel object, and you can set its data via the Int32 field and read / change individual color components.
Pixel p = new Pixel(); p.Int32 = pixelData[pixelIndex]; // index = x + y * stride if(p.Red < 165) { p.Int32 = 0; // Reset pixel p.Alpha = 255; // Make opaque pixelData[pixelIndex] = p.Int32; }
snarf source share