How do I convert a FILE* to an IStream!

Using GDI+, I want to save an HBITMAP to a disk file as JPG.

However, I am doing this within a legacy function that provides an already opened FILE* as a parameter.

I have found nothing in the docs.

static Bool sys_ImageToFileJPEG (HBITMAP hImage, FILE* pFile)
{
    Bool	fRet	= FALSE;

  if (hImage && pFile)
  {
      Gdiplus::Bitmap	image ((HBITMAP)hImage, (HPALETTE)0);

      if (image.GetLastStatus() == Gdiplus::Ok)
      {
          CLSID  encoderClsid;

          wimg_GetEncoderClsid (L"image/jpg", encoderClsid);

          // will not work - Save() wants an IStream!!!
          Gdiplus::Status hr = image.Save (pFile, &encoderClsid);

          if (Gdiplus::Ok == hr)
          {
             fRet = true;
          }
      }
  }

  return (fRet);
}
Ancient Dragon commented: Thanks for using code tags correctly +18

>> // will not work - Save() wants an IStream!!!
>> Gdiplus :: status hr = image.Save (pFile, &encoderClsid);

// ......
  IStream* pstm ; assert( CreateStreamOnHGlobal( 0, TRUE, &pstm ) >= 0 ) ;
  Gdiplus::Status hr = image.Save( pstm, &encoderClsid ) ;
  STATSTG stat ; assert( pstm->Stat( &stat, STATFLAG_NONAME ) >= 0 ) ;
  size_t sz = stat.cbSize.LowPart ; assert( stat.cbSize.HighPart == 0  ) ;
  HGLOBAL hg ; assert( GetHGlobalFromStream( pstm, &hg ) >= 0 ) ;
  assert( fwrite( GlobalLock(hg), sz, sz, pFile ) ==  sz ) ;
  GlobalUnlock(hg) ; pstm->Release() ;
// .....

Thanks! I will give this a try.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.