How To Properly Compress UIImages At Runtime

前端 未结 2 890
忘掉有多难
忘掉有多难 2021-01-14 02:22

I need to load 4 images for simultaneous editing. When I load them from the users library, the memory exceeds 500mb and crashes.

Here is a log from a raw allocations

2条回答
  •  隐瞒了意图╮
    2021-01-14 02:41

    The reason you're having crashes and seeing such high memory usage is that you are missing the call to UIGraphicsEndImageContext(); -- so you are leaking memory like crazy.

    For every call to UIGraphicsBeginImageContextWithOptions, make sure you have a call to UIGraphicsEndImageContext (after UIGraphicsGetImage*).

    Also, you should wrap in @autorelease (I'm presuming you're using ARC), otherwise you'll still have out-of-memory crashes if you are rapidly processing images.

    Do it like this:

    @autorelease {
      UIGraphicsBeginImageContextWithOptions(...);
      ..
      something = UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();
    }
    

提交回复
热议问题