GDI C/C++ - BITMAP into an existing HBITMAP

2.4k Views Asked by At

How can I create a device context compatible bitmap and then associating the obtained handle to a BITMAP struct? If I write:

...
HBITMAP hbitmap = CreateCompatibleBitmap(hdc, width, height); // these three arguments are initialized somewhere else
hbitmap = CreateBitmapIndirect(bitmap); // argument already initialized and properly filled
...

A HBITMAP handle compatible with hdc is created, and then a new HBITMAP (filled with bitmap data) is initialized, though without keeping its compatibility. Is there a function which allows not to create a HBITMAP from a BITMAP, but rather fills an initialized HBITMAP with an already existing BITMAP source?

2

There are 2 best solutions below

2
On

CreateBitmapIndirect takes BITMAP on its input. And you can get it via GetObject from HBITMAP:

BITMAP Bitmap;
INT nResult = GetObject((HGDIOBJ) hBitmap, sizeof Bitmap, &Bitmap);

CreateBitmapIndirect will be able create a bitmap from this struct. Or you can use CreateCompatibleBitmap to create compatible bitmap providing width/height from obtained Bitmap.

2
On

CopyImage function

Creates a new image (icon, cursor, or bitmap) and copies the attributes of the specified image to the new one. If necessary, the function stretches the bits to fit the desired size of the new image.

HANDLE WINAPI CopyImage(
  HANDLE hImage,
  UINT uType,
  int cxDesired,
  int cyDesired,
  UINT fuFlags
);

hImage A handle to the image to be copied.

uType The type of image to be copied. This parameter can be one of the following values.

  • IMAGE_BITMAP 0 Copies a bitmap.
  • IMAGE_ICON 1 Copies an icon.
  • IMAGE_CURSOR 2 Copies a cursor.

cxDesired The desired width, in pixels, of the image. If this is zero, then the returned image will have the same width as the original hImage.

cyDesired The desired height, in pixels, of the image. If this is zero, then the returned image will have the same height as the original hImage.

fuFlags