How To Properly Compress UIImages At Runtime

前端 未结 2 892
忘掉有多难
忘掉有多难 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)
    }
    

提交回复
热议问题