问题
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);
回答1:
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;
}
回答2:
You don't need an out
Bitmap. Just edit in
and save it. Also I'd advise using the CImage class instead
CImage image;
image.Load(filename);
fill [image] with whatever data you want
image.Save(filename);
来源:https://stackoverflow.com/questions/10673468/c-net-how-to-dispose-a-bitmap