裁剪位图,避免内存泄漏

huangapple go评论74阅读模式
英文:

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;

huangapple
  • 本文由 发表于 2023年6月13日 18:49:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76464114.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定