C ++ .NET - 如何处置一个位图? [英] C++ .NET - how to dispose a bitmap?
问题描述
我想从文件中加载一个位图,就可以执行某些操作,并将其保存回相同的文件名。该模式是这样的:
位图= gcnew位图(文件名);
位图OUT = gcnew位图(in.Width,in.Height,in.PixelFormat);填写[OUT]从数据[中]out.Save(文件名);
但是,这并不正常工作。这是显而易见的。我不能保存到它仍然是打开的(因为位图中)的文件。现在的问题是:如何赫克我在收位图?我尝试过很多方法,但没有任何工程。调用Dispose曾在C#中,但这种方法在C ++中保护。调用删除也不起作用。有什么解决办法?
编辑:
操作上一个位图也不起作用。但是,我发现了一个问题。调用delete工作。我忘了要申报位图指针
位图^ =中的位图gcnew(文件名);
位图^ OUT = gcnew位图(in.Width,in.Height,in.PixelFormat);填写[OUT]从数据[中]删除;
out.Save(文件名);
这是在C ++ / CLI编码一种常见的陷阱,你使用栈语义
。换句话说,你没有申报与 ^
帽子引用类型变量。这使得在编译的范围块结束时自动发出的Dispose()
电话。非常方便,在C RAII
模式的模拟++,但在这里碍事。你要保存新位图前处置在
位。
两种方法可以做到这一点。你可以通过添加括号玩范围盖帽:
位图^出来;
尝试{
{
在(文件名)位图;
OUT = gcnew位图(in.Width,in.Height,in.PixelFormat);
//等。
} //< ==中的在这里得到处理
输出>保存(文件名);
}
最后{
删除了;
}
但是,这是有点难看,特别是因为它需要在这个具体案例中混了退出
。另一种方法是刚做的一切明确的:
位图^出来;
位图^的;
尝试{
在= gcnew位图(文件名);
OUT = gcnew位图(包含在>宽度,在 - >的身高,在 - >的PixelFormat);
//等。
删除;
在= nullptr;
输出>保存(文件名);
}
最后{
删除;
删除了;
}
I want to load a bitmap from file, perform some operations on it, and save it back under the same file name. The pattern is this:
Bitmap in = gcnew Bitmap(fileName);
Bitmap out = gcnew Bitmap(in.Width, in.Height, in.PixelFormat);
fill [out] with data from [in]
out.Save(fileName);
but this doesn't work. That's obvious. I cannot save to a file which is still opened (because of bitmap in). The question is: how the heck do I close bitmap in?! I've tried many ways but nothing works. Calling Dispose worked in C# but this method is protected in C++. Calling delete also doesn't work. What's the solution?
EDIT: Operating on one bitmap doesn't work either. But I found a problem. Calling delete worked. I forgot to declare my bitmaps as pointers
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);
This is a common trap in C++/CLI coding, you are using stack semantics
. In other words, you didn't declare the reference type variable with the ^
hat. Which makes the compiler automatically emit the Dispose()
call at the end of the scope block. Very convenient and a simulation of the RAII
pattern in C++ but it gets in the way here. You want to dispose the in
bitmap before saving the new bitmap.
Two ways to do this. You could play a game with the scope blocks by adding braces:
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;
}
But that's kinda ugly, especially since it needs to be mixed up for out
in this very specific case. The alternative is to just do everything explicitly:
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;
}
这篇关于C ++ .NET - 如何处置一个位图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!