加载图片后程序崩溃(GDIplus)

时间:2014-05-26 16:04:24

标签: c++ windows gdi

我想编写一个程序来加载命令行给出的图像,然后用它做一些事情。我现在的问题是:每当我执行程序时,它会打印出图像的调色板大小(对于我输入的jpg格式的每张图片,它给出了错误的输出(12)),之后它崩溃了,但我无法弄清楚我的错。 我做错了什么?

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;
}

1 个答案:

答案 0 :(得分:0)

解决方案是:
写而不是

Gdiplus::Image image(wc);

这样:

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

这解决了我的问题。