0

I'm kind new to c#.

I have this code:

        public static BitmapSource FromNativePointer(IntPtr pData, int w, int h, int ch)
        {
            System.Windows.Media.PixelFormat format = System.Windows.Media.PixelFormats.Default;

            if (ch == 1) format = System.Windows.Media.PixelFormats.Gray8; //grey scale image 0-255
            if (ch == 3) format = System.Windows.Media.PixelFormats.Bgr24; //RGB
            if (ch == 4) format = System.Windows.Media.PixelFormats.Bgr32; //RGB + alpha

            WriteableBitmap wbm = new WriteableBitmap(w, h, (double)96, (double)96, format, null);

            CopyMemory(wbm.BackBuffer, pData, (uint)(w * h * ch));

            wbm.Lock();
            wbm.AddDirtyRect(new Int32Rect(0, 0, wbm.PixelWidth, wbm.PixelHeight));
            wbm.Unlock();

            return wbm;
        }

I'm having some memory problem with the wbm variable. How can I create the variable outside this function and then update its parameters only when I get in the function? Thank you.

Probst
  • 17
  • 1
  • 8
  • 1
    Can you be more specific about the memory problem you are having? – Robert Harvey May 07 '13 at 22:12
  • If you want to avoid the `new WriteableBitmap(...)`, you're going to have to implement it yourself using `Bitmap` and `BitmapData`, with some `MAX_WIDTH` and `MAX_HEIGHT`. Then, you can save it as a field and reuse it every time you need it. Note that this isn't thread-safe. – SimpleVar May 07 '13 at 23:24

2 Answers2

1

You can also make it a global/static variable.

public class Example(){
      public static WriteableBitmap wbm;
      .
      .
}
Maxito
  • 619
  • 11
  • 26
0

Just pass wbm as an additional parameter to the method. You don't even have to return it if you declare it in your parameter list as a ref:

public static void
    FromNativePointer(ref BitmapSource wbm, IntPtr pData, int w, int h, int ch)

If you declare it this way, you must also call it using ref:

FromNativePointer(ref mywbm, mypData ... etc.
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • And how will it be changed whenever he needs, according to `w` and `h`? – SimpleVar May 07 '13 at 22:20
  • What? He's already written the code to do that. Obviously, if a new `BitmapSource` is needed, a `new` `BitmapSource` will have to be created. – Robert Harvey May 07 '13 at 22:21
  • I don't wanna have to create a new wbm variable every time I get in this function. I wanna just update it. But I cant create like that `WriteableBitmap wbm = new WriteableBitmap(w, h, (double)96, (double)96, format, null);` outside the function because it will ask for w, h and format – Probst May 07 '13 at 22:35
  • I tried your way but once I add `ref BitmapSource wbm` I get errors cause I lose de definition of `BackBuffer` `Lock` `AddDirtyRect` `Unlock` – Probst May 07 '13 at 22:58