0

What is fast approach to manipulate pixels in WritableBitmap (i also use WritableBitmapEx extensions)? SetPixel is very slow method for things like filling a background for my Paint-like application and also it does some weird things like memory corruption (don't know why).

fex
  • 3,488
  • 5
  • 30
  • 46

1 Answers1

1

SetPixel very slow - it's true.

You should use the LockBits method, and then iterate all pixels using unsafe code (pointers for pixels).

Example:

// lock the bitmap.
var data = image.LockBits(
              new Rectangle(0, 0, image.Width, image.Height), 
              ImageLockMode.ReadWrite, image.PixelFormat);
try
{
    unsafe
    {
        // get a pointer to the data.
        byte* ptr = (byte*)data.Scan0;

        // loop over all the data.
        for (int i = 0; i < data.Height; i++)
        {
            for (int j = 0; j < data.Width; j++)
            {
                operate with pixels.
            }
        }
    }
}
finally
{
    // unlock the bits when done or when 
    // an exception has been thrown.
    image.UnlockBits(data);
}

I suggest you read this article.

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
Dzmitry Martavoi
  • 6,867
  • 6
  • 38
  • 59
  • Isn't having this in try finally block slows it down? I've read something that try blocks are pretty slow – fex Nov 01 '12 at 17:03
  • Try/finally can slow perfomance when u use it in a loop, but in this case it used once, there is practically no difference in perf. – Dzmitry Martavoi Nov 01 '12 at 20:05