views:

317

answers:

1

I know how to implement them, but what I don't know is whether to apply the transformation pixel by pixel or is there another way to affect the whole image, using a single call, etc?

AFAIK Get.Set Pixel is very slow. I am not sure if they did it this way.

So if it's the grayscale/desaturate filter as a simple case, how would one write it?

+5  A: 

You have to lock the image and then work with the memory directly bypassing SetPixel method. See here or even better here

For examle you can set the blue color to 255 as follows

   BitmapData bmd=bm.LockBits(new Rectangle(0, 0, 10, 10), System.Drawing.Imaging.ImageLockMode.ReadOnly, bm.PixelFormat);
      int PixelSize=4;
      for(int y=0; y<bmd.Height; y++)
      {
        byte* row=(byte *)bmd.Scan0+(y*bmd.Stride);
        for(int x=0; x<bmd.Width; x++)
        {
          row[x*PixelSize]=255;
        }
      } // it is copied from the last provided link.
Jenea
Thanks, I didn't know locking. What does lock does exactly? The link doesn't seem to go into detail with the description. Maybe the method name isn't very descriptive?
Joan Venge
Also with this method does one have to use unsafe code?
Joan Venge
It locks the memory to a physical location so that the .Net memory manager can't move it around during garbage collection. Yes this uses unsafe code and requires an appropriate unsafe{} section or compiler option.
Eric J.
Thanks, that makes sense.
Joan Venge
@Joan: using LockBits does require the unsafe keyword. This isn't normally a concern at all, but some Windows users can be running under security policies that prohibit unsafe code, so your app wouldn't work. I've never encountered this problem myself, but the threat of it has led me away from using Bitmaps at all. :(
MusiGenesis