4

I'm trying to convert a image file (a png, but could be anything) that I just extracted into memory from a compressed file to a ID2D1Bitmap to draw using Direct 2D. I tried to look for some documentation, but I can only find methods that receive "const char* path" or ask me width and height of my image, that I can't know before-hand. Searching on google for it got me nowhere.

The file is raw in memory, and I would like to avoid to extract images to the hdd into a temporary file just to read their data from there.

Any ideas?

Guilherme Amorim
  • 445
  • 5
  • 15
  • 1
    Use WIC to load it from an `IWICStream` and then use `CreateBitmapFromWicBitmap` to get your `ID2D1Bitmap` - there are examples on MSDN so I'm surprised you haven't found anything. – Roger Rowland Oct 28 '14 at 14:11
  • You have to first decode the image (for example using WIC) to raw RGB32 pixel data (this can be done in the memory), then you can use CreateBitmap() (http://msdn.microsoft.com/en-us/library/windows/desktop/jj841129%28v=vs.85%29.aspx). You should pass the pointer to the decoded image to srcData parameter. – Anton Angelov Oct 29 '14 at 15:56

1 Answers1

6

if you have the HBITMAP handle, you can do this:

  1. The the size of your image using: ::GetObject(hBmp, sizeof(BITMAP), &bmpSizeInfo);
  2. fill a BITMAPINFO like this: memset(&bmpData, 0, sizeof(BITMAPINFO)); bmpData.bmiHeader.biSize = sizeof(bmpData.bmiHeader); bmpData.bmiHeader.biHeight = -bmpSizeInfo.bmHeight; bmpData.bmiHeader.biWidth = bmpSizeInfo.bmWidth; bmpData.bmiHeader.biPlanes = bmpSizeInfo.bmPlanes; bmpData.bmiHeader.biBitCount = bmpSizeInfo.bmBitsPixel;

  3. create enough heap memory to hold the data for your bitmap: pBuff = new char[bmpSizeInfo.bmWidth * bmpSizeInfo.bmHeight * 4];

  4. Get the bitmap data like this: ::GetDIBits(hDc, hBmp, 0, bmpSizeInfo.bmHeight, (void*)pBuff, &bmpData, DIB_RGB_COLORS);

  5. Create a D2D1_BITMAP_PROPERTIES and fill it like this: bmpPorp.dpiX = 0.0f; bmpPorp.dpiY = 0.0f; bmpPorp.pixelFormat.format = DXGI_FORMAT_B8G8R8A8_UNORM; bmpPorp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_IGNORE;

  6. Using your render target turn the data into ID2D1Bitmap pRT->CreateBitmap(bmpSize, pBuff, 4 * bmpSizeInfo.bmWidth, bmpPorp, &pBmpFromH);

Hope this can help.

Sam

Sam
  • 2,473
  • 3
  • 18
  • 29
  • Great, This is what I was looking for. For a long time beating my head around the keyboard. – iamrameshkumar Jul 19 '17 at 09:32
  • 1
    @Ram Don't forget to delete the buffer created in heap (**pBuff**) like `delete[] pBuff;` – Sam Jul 20 '17 at 17:19
  • So to just creating a bitmap in memory and rendering it with Direct2D does not open the can of WIC-Worms, right?! :) – BitTickler Feb 11 '20 at 13:19
  • @BitTickler You are correct, this method directly transforms the image from GDI's HBITMAP to ID2D1Bitmap. No WIC is involved. – Sam Feb 12 '20 at 20:35