Click here to Skip to main content
Click here to Skip to main content

Converting between different image formats (using GDI+)

By , 5 Jan 2011
 
Given an input stream of some type of image, the following function converts that image into another type of image given the destination format. The destination format should be a proper mime-type such as "image/jpeg", "image/png".
Gdiplus::Status imageToImage(
  IStream *pStreamIn, IStream *pStreamOut, BSTR wszOutputMimeType)
{
    namespace G = Gdiplus;
    G::Status status = G::Ok;
    G::Image imageSrc(pStreamIn);
    status = imageSrc.GetLastStatus();
    if (G::Ok != status) {
      return status;
    }
    UINT numEncoders = 0;
    UINT sizeEncodersInBytes = 0;
    status = G::GetImageEncodersSize(&numEncoders, &sizeEncodersInBytes);
    if (status != G::Ok) {
      return status;
    }
    G::ImageCodecInfo *pImageCodecInfo = 
         (G::ImageCodecInfo *) malloc(sizeEncodersInBytes);
    status = G::GetImageEncoders(
          numEncoders, sizeEncodersInBytes, pImageCodecInfo);
    if (status != G::Ok) {
      return status;
    }
    CLSID clsidOut;
    status = G::UnknownImageFormat;
    for (UINT j = 0; j < numEncoders; j ++) {
      if (0 == wcscmp(pImageCodecInfo[j].MimeType, wszOutputMimeType)) {
        clsidOut = pImageCodecInfo[j].Clsid;
        status = G::Ok;
        break;
      }    
    }
    free(pImageCodecInfo);
    if (status != G::Ok) {
      return status;
    }
    return imageSrc.Save(pStreamOut, &clsidOut);
  }
It can be used like so:
extern IStream *pSomeImg; // source image format is not important
extern IStream *pMyJpeg;
if (Gdiplus::Ok == imageToImage(pSomeImg, pMyJpeg, L"image/jpeg")) {
// pMyJpeg holds the converted jpeg.
}
If there is a need to put/retrieve data into/from IStream in byte-array format (such as char*), it can by done by using CreateStreamOnHGlobal, GlobalAlloc, GlobalLock Win32 API functions. See this tip for more details.
 
Note: List of supported formats: BMP, ICON, GIF, JPEG, Exif, PNG, TIFF, WMF, and EMF.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Arman S.
Software Developer 13
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 5 Jan 2011
Article Copyright 2010 by Arman S.
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid