C#中:如何使用位图时减少内存和CPU的消耗? [英] C#: How to reduce memory and CPU consumption when working with Bitmaps?

查看:204
本文介绍了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);
    }

我应该用什么样的方法来避免这种情况?
我已经尝试过COM $ P $几种格式它pssing内存流,但它并没有帮助(甚至使病情加重)

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

推荐答案

您code为创建图像的副本,所以你应该想到非托管的内存使用,当你调用这些方法上升。要紧的一个伟大的交易是你原来做什么。你会是明智的,摆脱它,使其不再占用内存。你必须调用它的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的消耗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆