locked
Save bitmap to global memory RRS feed

  • Question

  • I have a Bitmap object and want to create a bmp-file in a global memory using the save Method with an Istream Interface. How can I obtain the size of the bmp file before streaming it to my global memory??
    Monday, June 29, 2009 3:12 PM

Answers

  • Chicken-and-egg problem, you don't really know until you've serialized the bitmap.  You can certainly calculate the size from the BITMAPINFOHEADER.  But avoid getting that wrong by using an IStream implementation that knows how to expand the memory allocation when necessary.  CreateStreamOnHGlobal() fits that bill.

    Hans Passant.
    • Proposed as answer by jinzai Thursday, July 2, 2009 2:29 PM
    • Marked as answer by nobugz Thursday, July 2, 2009 2:44 PM
    Monday, June 29, 2009 3:35 PM

All replies

  • Chicken-and-egg problem, you don't really know until you've serialized the bitmap.  You can certainly calculate the size from the BITMAPINFOHEADER.  But avoid getting that wrong by using an IStream implementation that knows how to expand the memory allocation when necessary.  CreateStreamOnHGlobal() fits that bill.

    Hans Passant.
    • Proposed as answer by jinzai Thursday, July 2, 2009 2:29 PM
    • Marked as answer by nobugz Thursday, July 2, 2009 2:44 PM
    Monday, June 29, 2009 3:35 PM
  • The Bitmap has a width, height and bpp. The size depends on the specific format, which is documented in many places.
    Monday, June 29, 2009 3:38 PM
  • Was successful with CreateStreamOnHGlobal(...) Thanx!

    Bitmap *bitmap;
    HGLOBAL hMem;
    IStream *stream;
    LPVOID pImage, pMem;
    CLSID encoderCLSID;
    DWORD bmpSize;

    bitmap = new Bitmap((**phAreaData)->PictDef.PictWidth,
    (**phAreaData)->PictDef.PictHeight,
    PixelFormat32bppPARGB);

    .... // fill the bitmap
    // calculate bitmap size
    bmpSize = bitmap->GetWidth() * bitmap->GetHeight() * 4 + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
    // Create a global memory
    hMem = ::GlobalAlloc(GMEM_MOVEABLE, bmpSize);
    // Create a stream object from the global memory
    CreateStreamOnHGlobal(hMem, true, &stream);
    // Save bitmap to iStream
    GetEncoderClsid(L"image/bmp", &encoderCLSID);
    bitmap->Save(stream, &encoderCLSID);
    pMem = ::GlobalLock(hMem);
    // custom function
    pict = CreatePicture(pMem, bmpSize);
    ::GlobalUnlock(hMem);
    stream->Release();
    Wednesday, July 1, 2009 11:21 AM