How To Properly Compress UIImages At Runtime

前端 未结 2 891
忘掉有多难
忘掉有多难 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:25

    I ended up hard coding a size reduction before processing the image. Here is the code:

    PHImageManager.defaultManager().requestImageForAsset(asset, targetSize:CGSizeMake(CGFloat(asset.pixelWidth), CGFloat(asset.pixelHeight)), contentMode: .AspectFill, options: options)
    {
      result, info in
      var minRatio:CGFloat = 1
      //Reduce file size so take 1/2 UIScreen.mainScreen().bounds.width/2 || CGFloat(asset.pixelHeight) > UIScreen.mainScreen().bounds.height/2)
      {
        minRatio = min((UIScreen.mainScreen().bounds.width/2)/(CGFloat(asset.pixelWidth)), ((UIScreen.mainScreen().bounds.height/2)/CGFloat(asset.pixelHeight)))
      }
    
      var size:CGSize = CGSizeMake((CGFloat(asset.pixelWidth)*minRatio),(CGFloat(asset.pixelHeight)*minRatio))
      UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
      result.drawInRect(CGRectMake(0, 0, size.width, size.height))
      var final = UIGraphicsGetImageFromCurrentImageContext()
      var image = iImage(uiimage: final)
    }
    
    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
提交回复
热议问题