question

DeepakGunasekaran-1724 avatar image
0 Votes"
DeepakGunasekaran-1724 asked DeepakGunasekaran-1724 commented

CreateCompatabileBitmap background is always Black

I am using P-Invoke to create Compatible Bitmap in WPF as I need to work with handle. The following code provide me image with Black backgroud. I need to have White background. Can anyone please help me on this?

My code details are below

         [DllImport("User32.dll")]
         public extern static System.IntPtr GetDC(System.IntPtr hWnd);
    
         [DllImport("Gdi32.dll")]
         public extern static System.IntPtr CreateCompatibleDC(IntPtr hDC);
    
         [DllImport("Gdi32.dll")]
         public extern static IntPtr CreateCompatibleBitmap(IntPtr hdc, int cx,int cy);
    
         [DllImport("Gdi32.dll")]
         public extern static IntPtr SelectObject(IntPtr compatibleDC, IntPtr compatibleBitmap);
    


             IntPtr hdc = System.IntPtr.Zero;
             System.IntPtr deviceHandle = GetDC(hdc);
             IntPtr compatibleDC = CreateCompatibleDC(hdc);
    
             IntPtr compatibleBitmap = CreateCompatibleBitmap(deviceHandle, 545, 850);
             IntPtr oldBitmapHandle = SelectObject(compatibleDC, compatibleBitmap);
    
             SelectObject(compatibleDC, oldBitmapHandle);
    
             Bitmap myBitmap = Bitmap.FromHbitmap(compatibleBitmap);
             myBitmap.Save("output.png");





dotnet-csharpwindows-wpfc++
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Castorix31 avatar image
0 Votes"
Castorix31 answered DeepakGunasekaran-1724 commented

It is black by default
You can fill it with PatBlt for example :

 IntPtr oldBitmapHandle = SelectObject(compatibleDC, compatibleBitmap);                
 PatBlt(compatibleDC, 0, 0, 545, 850, WHITENESS);

with :

         [DllImport("Gdi32.dll", SetLastError = true)]
         public static extern bool PatBlt(IntPtr hdc, int x, int y, int w, int h, uint rop);
    
         public const int WHITENESS = 0x00FF0062;

(and you must release/delete GDI objects at end...)



· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

That's awesome. Thank you so much.

0 Votes 0 ·