問題描述
我有一個處理圖像編輯(裁剪和調整大小)的 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);
}
我應該使用什么方法來避免這種情況?我已經(jīng)嘗試將其壓縮為多種格式的內存流,但沒有幫助(甚至更糟)
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
推薦答案
您的代碼正在創(chuàng)建圖像的副本,因此當您調用這些方法時,您應該預料到非托管內存使用量會增加.重要的是你如何處理原件.你最好擺脫它,這樣它就不再占用內存.您必須調用它的 Dispose() 方法才能這樣做.等待垃圾收集器執(zhí)行它需要太長時間.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 消耗?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!