Skip to main content
 首页 » 编程设计

c#之如何使用 UIImage.FromImage(context.ToImage()) 防止内存泄漏

2024年02月20日15lautakyan007

我有以下函数可以将像素字节数组转换为图像。但是,我在行中有内存泄漏:

unpackedImage = UIImage.FromImage(context.ToImage());

当我注释掉上面的行时,泄漏就消失了。泄漏非常严重,iOS 在启动后大约 30 秒内杀死了我的应用程序。就是因为这行代码。

如何防止这种内存泄漏?有没有更好的方法来完成我想做的事情?

    public static void DrawCustomImage2(IntPtr buffer, int width, int height, int bytesPerRow, CGColorSpace colSpace, byte[] rawPixels, ref UIImage unpackedImage) 
    { 
        GCHandle pinnedArray = GCHandle.Alloc(rawPixels, GCHandleType.Pinned); 
        IntPtr pointer = pinnedArray.AddrOfPinnedObject(); 
 
        // Set a grayscale drawing context using the image buffer 
        CGBitmapContext context = new CGBitmapContext(pointer, width, height, 8, bytesPerRow, colSpace, CGImageAlphaInfo.None); 
 
        // Turning off interpolation and Antialiasing is supposed to speed things up 
        context.InterpolationQuality = CGInterpolationQuality.None; 
        context.SetAllowsAntialiasing(false); 
 
        try 
        { 
            unpackedImage = UIImage.FromImage(context.ToImage());   // Convert the drawing context to an image and set it as the unpacked image 
        } finally 
        { 
            pinnedArray.Free(); 
            if (context != null) 
                context.Dispose(); 
        } 
    } 

这是分析截图(注释掉关键代码行时,选中的项目全部消失)。您可以看到检查的项目(尤其是 Malloc)如何随时间增长。

这是 Malloc 1.50KB 的放大 View 。您可以在右侧的扩展详细信息 Pane 中看到它正在调用 CGBitmapContextCreateImage 和 CGDataProviderCreateWithCopyOfData,然后是 malloc。

这是 Rolf 建议的分析截图。我运行了两次图像循环。你可以看到它在第一次循环结束时清理了额外的内存,但是系统第二次清理的速度不够快,iOS 杀死了我的应用程序(你可以看到右上角的低内存警告标志角落)。

请您参考如下方法:

这样做:

using (var pool = new NSAutoreleasePool ()) { 
    using (var img = context.ToImage ()) { 
        unpackedImage = UIImage.FromImage (img);  
    } 
}