0

我想从文件中加载位图,对其执行一些操作,然后将其保存在相同的文件名下。模式是这样的:

Bitmap in = gcnew Bitmap(fileName);
Bitmap out = gcnew Bitmap(in.Width, in.Height, in.PixelFormat);

fill [out] with data from [in]

out.Save(fileName);

但这不起作用。这很明显。我无法保存到仍然打开的文件(因为位图)。问题是:我到底要如何关闭位图?!我尝试了很多方法,但没有任何效果。调用 Dispose 在 C# 中工作,但此方法在 C++ 中受保护。调用删除也不起作用。解决方案是什么?

编辑:在一个位图上操作也不起作用。但是我发现了一个问题。调用删除工作。我忘了将我的位图声明为指针

Bitmap^ in = gcnew Bitmap(fileName);
Bitmap^ out = gcnew Bitmap(in.Width, in.Height, in.PixelFormat);

fill [out] with data from [in]

delete in;
out.Save(fileName);
4

2 回答 2

1

这是 C++/CLI 编码中的常见陷阱,您正在使用stack semantics. 换句话说,您没有用^帽子声明引用类型变量。这使得编译器Dispose()在作用域块的末尾自动发出调用。非常方便,并且是RAIIC++ 中模式的模拟,但它在这里妨碍了。您想in在保存新位图之前处理位图。

有两种方法可以做到这一点。您可以通过添加大括号来使用范围块玩游戏:

Bitmap^ out;
try {
    {
        Bitmap in(fileName);
        out = gcnew Bitmap(in.Width, in.Height, in.PixelFormat);
        // etc..
    }   // <== "in" gets disposed here
    out->Save(fileName);
}
finally {
    delete out;
}

out但这有点难看,特别是因为在这种非常具体的情况下需要混合起来。另一种方法是明确地做所有事情:

Bitmap^ out;
Bitmap^ in;
try {
    in = gcnew Bitmap(fileName);
    out = gcnew Bitmap(in->Width, in->Height, in->PixelFormat);
    // etc..
    delete in;
    in = nullptr;
    out->Save(fileName);
}
finally {
    delete in;
    delete out;
}
于 2012-05-20T13:18:20.040 回答
0

您不需要out位图。只需编辑in并保存即可。我也建议改用 CImage 类

CImage image;
image.Load(filename);
fill [image] with whatever data you want
image.Save(filename);
于 2012-05-20T12:44:00.857 回答