1

I have a function that takes a color bitmap and makes it greyscale, but the memory usage is far too high. I used the Marshal.Copy method before, there is not memory leak but its slower. Any help?

        Bitmap b = a.Clone(new Rectangle(0, 0, a.Width, a.Height), a.PixelFormat);
        BitmapData bData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, b.PixelFormat);
        byte bitsPerPixel = Convert.ToByte(Image.GetPixelFormatSize(bData.PixelFormat));

        /*This time we convert the IntPtr to a ptr*/
        byte* scan0 = (byte*)bData.Scan0.ToPointer();

        //Console.WriteLine(scan0);
        for (int i = 0; i < bData.Height; ++i)
        {
            for (int j = 0; j < bData.Width; ++j)
            {
                byte* data = scan0 + i * bData.Stride + j * bitsPerPixel / 8;

                data[0] = data[1] = data[2] = (byte)((data[0] + data[1] + data[2]) / 3);

            }
        }
        b.UnlockBits(bData);
        bData = null;
        return b;
Jon
  • 11
  • 1

2 Answers2

1

I don't know about the memory leak but there is a better way to convert image to greyscale. Visit this page, you'll find three ways to do it, with third way called "Short and Sweet" being the fastest. And sweetest.

External site is unavailable even in Google and Internet Archive's wayback machine, but the code for short and sweet method is given in another SO answer.

Community
  • 1
  • 1
Dialecticus
  • 15,040
  • 5
  • 36
  • 88
0

If you want to write straight to memory pointers from within C#, you need to use "unsafe code". See the article here for more info:

http://msdn.microsoft.com/en-us/library/aa288474(VS.71).aspx

Bret Savage
  • 201
  • 1
  • 6