C#:在使用位图时减少内存和 CPU 消耗?
问题说明
我有一个处理图像编辑(裁剪和调整大小)的 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.
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tangicaic
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
检查邮件是否发送成功
it1352 07-25 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20