英文:
Crop Bitmap without memory leak
问题
我有一个仅裁剪位图的函数。
public static Bitmap cropImage(Bitmap FullBmp, int leftBorder, int topBorder)
{
return FullBmp.Clone(new Rectangle(leftBorder, topBorder, FullBmp.Width, FullBmp.Height - topBorder), FullBmp.PixelFormat);
}
这段代码有效,但会导致内存泄漏。使用这个函数会导致内存泄漏:
我大致明白为什么会发生这种情况,但我无法修复这个内存泄漏。我尝试使用Graphics.DrawImage但没有成功。
英文:
I have a function which only crops Bitmap.
public static Bitmap cropImage(Bitmap FullBmp, int leftBorder, int topBorder)
{
return FullBmp.Clone(new Rectangle(leftBorder, topBorder, FullBmp.Width, FullBmp.Height - topBorder), FullBmp.PixelFormat);
}
This code works, however it creates huge memory leak. With this function:
And without:
I approximately understand why this happens, but I can't fix this memory leak. I tried to use Graphics.DrawImage but without success.
答案1
得分: 1
你释放了原始位图引用,但没有释放资源,因此这将依赖于垃圾回收周期来执行此操作。
要强制释放内存,您应该这样做:
var baslerImg_n = ImageManipulation.cropImage(baslerImg, 0, 650);
baslerImg.Dispose();
baslerImg = baslerImg_n;
英文:
You are releasing the original bitmap reference without releasing resources so it will depend on GC cycle to do this.
to enforce releasing memory you should do this:
var baslerImg_n = ImageManipulation.cropImage(baslerImg, 0, 650);
baslerImg.Dispose();
baslerImg = baslerImg_n;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论