Jon
Jon

Reputation: 11

excessive memory usage when using pointers?

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;

Upvotes: 1

Views: 145

Answers (2)

Dialecticus
Dialecticus

Reputation: 16761

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.

Upvotes: 1

Bret Savage
Bret Savage

Reputation: 201

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

Upvotes: 0

Related Questions