问题描述
我有一个处理图像编辑(裁剪和调整大小)的 Windows 应用程序项目.不幸的是,这些图像处理会消耗大量内存和 CPU 资源(很容易达到 600MB 或 50% 的 cpu),而且只需要裁剪和调整一张 2.5MB (2300*5400px) 的 gif 图像.更重要的是,由于资源消耗大,程序在调整大小时卡住......
I have a Windows Application project that deals with Image editing (Cropping & Resizing). Unfortunately these image processings consume a lot of Memory and CPU resources (easily reaches 600MB or 50% cpu) and it is all about cropping and resizing just one gif image that weighs 2.5MB (2300*5400px). More than that, due to large resource consumption, the program gets stuck while resizing...
public static Image Resize(Image imgToResize, Size size)
{
Bitmap b = new Bitmap(size.Width, size.Height);
Graphics g = Graphics.FromImage((Image)b);
g.InterpolationMode = InterpolationMode.Default;
g.SmoothingMode = SmoothingMode.HighSpeed;
g.PixelOffsetMode = PixelOffsetMode.Default;
g.DrawImage(imgToResize, 0, 0, size.Width, size.Height);
g.Dispose();
return (Image)b;
}
public static Image Crop(Image img, Point p1, Point p2)
{
Rectangle cropArea = new Rectangle(p1.X, p1.Y, p2.X - p1.X, p2.Y - p1.Y);
return (img as Bitmap).Clone(cropArea, img.PixelFormat);
}
我应该使用什么方法来避免这种情况?我已经尝试将其压缩为多种格式的内存流,但没有帮助(甚至更糟)
What methods should I use to avoid this? I've already tried compressing it to memory stream in several formats but it didn't help (even made it worse)
注意:我使用标准的 .NET 绘图库:System.Drawing、System.Drawing.Imaging
NOTE: I use the standard .NET Drawing libraries: System.Drawing, System.Drawing.Imaging
推荐答案
您的代码正在创建图像的副本,因此当您调用这些方法时,您应该预料到非托管内存使用量会增加.重要的是你如何处理原件.你最好摆脱它,这样它就不再占用内存.您必须调用它的 Dispose() 方法才能这样做.等待垃圾收集器执行它需要太长时间.Bitmap 类占用很少的托管内存,但占用大量非托管内存.
Your code is creating copies of the image so you should expect unmanaged memory usage to rise when you call these methods. What matters a great deal is what you do with the original. You would be wise to get rid of it so it no longer takes up memory. You have to call its Dispose() method to do so. Waiting for the garbage collector to do it takes too long. The Bitmap class takes very little managed memory but oodles of unmanaged memory.
这篇关于C#:如何在使用位图时减少内存和 CPU 消耗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!