【问题标题】:Program crashes after loading image (GDIplus)加载图像后程序崩溃(GDIplus)
【发布时间】:2014-05-27 01:18:46
【问题描述】:

我想写一个程序来加载命令行给出的图像,然后用它做一些事情。我现在的问题是:每当我执行程序时,它都会打印我图像的调色板大小(这给我输入的每张 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;
}

【问题讨论】:

  • num_colors = (int)argv[2]; 将指针转换为整数,而不是解析字符串。使用例如std::stoi.
  • 我知道,但我不认为这是导致崩溃的原因。
  • 格式字符串L"%hs"是什么意思
  • 我希望如果你传入一个错误的文件名,获取调色板大小可能不起作用......
  • 我可以重现崩溃(with 初始化启动信息),并且在动态分配图像对象时它会消失。我不知道怎么了。

标签: c++ windows gdi


【解决方案1】:

解决办法是:
写作而不是

Gdiplus::Image image(wc);

这个:

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

这解决了我的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    相关资源
    最近更新 更多