Click here to Skip to main content
13,288,520 members (61,373 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


17 bookmarked
Posted 28 Dec 2010

Converting between different image formats (using GDI+)

, 5 Jan 2011
Rate this:
Please Sign up or sign in to vote.
Shows how to convert between different image formats by using GDI+
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;
    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.


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
No Biography provided

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171207.1 | Last Updated 5 Jan 2011
Article Copyright 2010 by Arman S.
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid