Convert DIB or BMP into JPEG in memory (diskless) using Windows GDIPlus

    
    #include 
    #include 

    using namespace Gdiplus;

    GdiplusStartupInput gdiplusStartupInput;
    ULONG_PTR gdiplusToken;
    GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
    ...
    IStream* pJpegStream = NULL;  //declare a memory stream
    CreateStreamOnHGlobal(NULL, TRUE, (LPSTREAM*)&pJpegStream);

    GpBitmap* pBitmap = NULL;
    unsigned char* dib = GetDib(); //get DIB or BMP data buffer
    DllExports::GdipCreateBitmapFromGdiDib((LPBITMAPINFO)dib, dib + sizeof(BITMAPINFOHEADER), &pBitmap);

    CLSID imageCLSID;
    GetEncoderClsid(L"image/jpeg", &imageCLSID);

    int jpegQuality = 100;

    EncoderParameters encoderParams; //setup jpeg encoder parameters
    encoderParams.Count = 1;
    encoderParams.Parameter[0].NumberOfValues = 1;
    encoderParams.Parameter[0].Guid = EncoderQuality;
    encoderParams.Parameter[0].Type = EncoderParameterValueTypeLong;
    encoderParams.Parameter[0].Value = &jpegQuality;

    //save jpeg into memory stream
    DllExports::GdipSaveImageToStream(pBitmap, pJpegStream, &imageCLSID, &encoderParams);

    LARGE_INTEGER lnOffset;
    lnOffset.QuadPart = 0;
    ULARGE_INTEGER ulnSize;
    //determine memory stream length
    pJpegStream->Seek(lnOffset, STREAM_SEEK_END, &ulnSize);
    pJpegStream->Seek(lnOffset, STREAM_SEEK_SET, NULL);
    int encodedBytes = ulnSize.QuadPart;
    
    //store jpeg memory stream into jpeg data buffer
    pJpegStream->Read(racBuf_, ulnSize.QuadPart, NULL);
    ...
    GdiplusShutdown(gdiplusToken);