【问题标题】:How to fix memory issue with image processing?如何解决图像处理的内存问题?
【发布时间】:2019-08-31 04:50:39
【问题描述】:

我正在创建 gif 拆分器,它从给定的 gif 文件返回图像序列,它适用于小尺寸的 gif,一切看起来都符合预期,但大文件(大于 500×500 像素)会导致内存问题。

Xcode 消息:来自调试器的消息:由于内存问题而终止 “连接中断”通信错误

比这个问题更大,我在 XCode 分析器中看不到任何泄漏或负载,内存使用量显示在 50 - 110 mb 之间?!

我尝试更改gifOptions,但没有任何改变。

import UIKit
import ImageIO
import MobileCoreServices 

class CGifManager { 

  static let shared = CGifManager()

  public func getSequence(gifNamed: String) -> [UIImage]? { 
     guard let bundleURL = Bundle.main .url(forResource: gifNamed, withExtension: "gif") else { 
       print("This image named \"\(gifNamed)\" does not exist!"); return nil 
     } 

     guard let imageData = try? Data(contentsOf: bundleURL) else { 
       print("Cannot turn image named \"\(gifNamed)\" into NSData") return nil 
     } 

     let gifOptions = [ kCGImageSourceShouldAllowFloat as String : true as NSNumber, 
                        kCGImageSourceCreateThumbnailWithTransform as String : true as NSNumber, 
                        kCGImageSourceCreateThumbnailFromImageAlways as String : true as NSNumber 
                       ] as CFDictionary 
     guard let imageSource = CGImageSourceCreateWithData(imageData as CFData, gifOptions) else {
       debugPrint("Cannot create image source with data!"); return nil 
      } 

      let framesCount = CGImageSourceGetCount(imageSource) 
      var frameList = [UIImage]() 
      for index in 0 ..< framesCount { 
         if let cgImageRef = CGImageSourceCreateImageAtIndex(imageSource, index, nil) { 
            let uiImageRef = UIImage(cgImage: cgImageRef) 
            frameList.append(uiImageRef) 
         } 
      } 
      return frameList 
    }
  }

此代码使用 400 x 400 和 400 x 500(30 帧)大小的 gif 进行测试,效果也很好,但实际上我需要使用所有尺寸,所以我不知道问题出在哪里?

任何可以接受的帮助。

【问题讨论】:

    标签: swift image memory-leaks gif


    【解决方案1】:

    这是您的主要问题之一的根源:

    var frameList = [UIImage]() 
    

    警钟!在内存中保存一组 UIImages 是耗尽内存的好方法。将图像保存到磁盘并制作一组名称或 URL。

    【讨论】:

    • 另外我注意到您的gifOptions 不包含阻止缓存的选项。
    • 我向上帝发誓我无法理解,今天一切正常,没有内存问题也没有泄漏,现在当我生成带有图像序列的 gif 文件时也会出现同样的问题。实际上我正在尝试制作 VImage 应用程序;它是如何工作的?我得到了选定的图像和 gif,而不是将 gif 拆分为帧,以便可以将选定的图像添加为像背景图像一样的蒙版,并再次从这些蒙版图像序列生成 gif,它看起来像视频 (VImage)。
    • 将图像存储在数组中的原因是我会立即使用它们,这就是为什么不需要再次保存和获取但可能我需要想办法清除这个数组。
    猜你喜欢
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 2021-12-03
    • 2021-12-19
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    相关资源
    最近更新 更多