Search code examples
c++windowsgdi

Program crashes after loading image (GDIplus)


I wanted to write a program which loads an image given by command line and afterwards does something with it. My problem now is: Whenever I execute the program it prints me the palette size of the image (which gives me a wrong output (12) for every picture in jpg format I enter), and afterwards it crashes, but I can not figure out my mistake. What am I doing wrong?

inline bool exists(const std::string& name) {
    if (FILE *file = fopen(name.c_str(), "r")) {
        fclose(file);
        return true;
    }
    else {
        return false;
    }
}

int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        std::cout << "Too few/too much arguments. Usage: ShrinkImage <Input-File> <Number of target colours>\n";
        return 0;
    }
    int num_colors;
    char * filepath = argv[1];
    if (!exists(filepath))
    {
        std::cout << "File does not exist.\n";
        return 0;
    }
    num_colors = std::stoi(argv[2], nullptr);
    ULONG_PTR(m_gdiplusToken);
    Gdiplus::GdiplusStartupInput gdiplusstartupinput;
    Gdiplus::GdiplusStartup(&m_gdiplusToken, &gdiplusstartupinput, NULL);
    const size_t cSize = strlen(filepath) + 1;
    size_t Size = cSize - 1;
    wchar_t *wc = new wchar_t[cSize];
    swprintf(wc, cSize, L"%hs", filepath);
    Gdiplus::Image image(wc);
    std::cout << image.GetPaletteSize() << '\n';
    std::cout << "Printed PaletteSize\n";

    delete wc;
    Gdiplus::GdiplusShutdown(m_gdiplusToken);
    std::cout << "After Shutdown\n";
    return 0;
}

Solution

  • Solution is:
    Writing instead of

    Gdiplus::Image image(wc);
    

    this:

    Gdiplus::Image * image = Gdiplus::Image::FromFile(wc);
    delete image;
    image = 0;
    

    This solves my problem.