[C++] Start using GDI+ Library in c++

2019. 8. 1. 22:19Development/C++

using gdiplus in c++, mfc

When you develop a Windows program, you often need to work on the UI. In this case, we mainly use the gdiplus.dll library. There is a problem in getting the code and running it, but there is no problem.

This is when gdiplus is not initialized. To use the gdiplus library, you must initialize it.

#include <gdiplus.h>
#pragma comment(lib, "gdiplus")

To use GDI +, all you need to do is declare it like this:

You can add a lib file over the code without adding lib in the project properties via #pragma comment (lib, "xxx").

 

GdiplusStartup

ULONG_PTR gdiplus_token;
GdiplusStartupInput gdiplus_startup_input;

if (Gdiplus::Status::Ok != ::GdiplusStartup(&gdiplus_token, &gdiplus_startup_input, NULL)) {
    
    //
    // error.
    //
    
    // ...
}

If an error occurs in the above GdiplusStartup, a value other than Gdiplus :: Status :: OK will be returned and the GDI+ API will not work normally.

GdiplusShutdown

GdiplusShutdown(gdiplus_token);

After everything is done, you need to call GdiplusShutdown to clean up GDI+.

Example

#include <gdiplus.h>
#pragma comment(lib, "gdiplus")

void gdiplus_example() {

    do {

        //
        // initialize GDI+
        //

        ULONG_PTR gdiplus_token;
        GdiplusStartupInput gdiplus_startup_input;
        if (Gdiplus::Status::Ok != ::GdiplusStartup(&gdiplus_token, &gdiplus_startup_input, NULL)) {

            //
            // error.
            //

            break;
        }

        //
        // load image.
        //

        // Gdiplus::Image* image = Gdiplus::Image::FromFile(L"image.jpg");
        Gdiplus::Image* image = new Gdiplus::Image(L"image.jpg");


        //
        // verify.
        //

        if (nullptr == image) {
            // ...
        }
        else {

            if (Gdiplus::Ok != image->GetLastStatus()) {
                delete image;
                image = nullptr;
            }
        }


        //
        // use image.
        //

        // todo.


        //
        // delete image.
        //

        if (nullptr != image) {
            delete image;
            image = nullptr;
        }


        //
        // Finalize GDI+
        //

        GdiplusShutdown(gdiplus_token);

    } while (false);
    
}

Precautions when using GDI+

  • Do not call the GDI+ API before calling GdiplusStartup.
  • You must release all GDI+ objects before calling GdiplusShutdown.
  • Do not initialize GDI+ in dllmain. (Do not call GdiplusStartup or GdiplusShutdown in dllmain)