【问题标题】:UIImage array to PDF Converting Memory LeakUIImage 数组到 PDF 转换内存泄漏
【发布时间】:2018-11-20 11:31:07
【问题描述】:

我想在 PDF 文档上合并 UIImage,然后它作为数据发送到 API。

但是在这种方法中,存在很大的内存泄漏!它从 20 MB 开始,然后上升到 390 MB,最后内存稳定在 300 MB。

这个方法有什么问题?

fileprivate func mergeImages(_ images: Array<UIImage>)  {
    DispatchQueue.global(qos: .utility).sync {
        let width: CGFloat = 768
        let height: CGFloat = 1024
        let pageSize = CGSize(width: width, height: height);
        let pageFrame = CGRect(x: 0, y: 0, width: width, height: height);
        let pdfData = NSMutableData()

        UIGraphicsBeginPDFContextToData(pdfData, pageFrame, nil)
        let ctx = UIGraphicsGetCurrentContext()

        for i in 0 ..< images.count {
            autoreleasepool {
                let jpegData = UIImageJPEGRepresentation(images[i].resize(toSize: pageSize)!, 0.8)
                let dp = CGDataProvider(data: jpegData! as CFData)
                let cgImage = CGImage(jpegDataProviderSource: dp!, decode: nil, shouldInterpolate: true, intent: .defaultIntent)

                UIGraphicsBeginPDFPage()
                ctx?.translateBy(x: 0, y: height)
                ctx?.scaleBy(x: 1.0, y: -1.0)
                ctx?.draw(cgImage!, in: pageFrame)
            }
            //image.drawInRect(pageFrame)
        }

        UIGraphicsEndPDFContext()
        let d = pdfData as Data
        self.completion?(d)
    }        
}

【问题讨论】:

  • 您应该查看“调试内存图”以验证内存是否泄漏。如果是这样,它将为您提供一些信息来解决问题。
  • @tersintersi 为什么你使用 CGImage 对象而不是直接绘制 UIImage 对象本身。

标签: ios swift pdf memory memory-leaks


【解决方案1】:

请尝试对这些对象使用 CGRelease 方法

let jpegData = UIImageJPEGRepresentation(images[i].resize(toSize: pageSize)!, 0.8)
let dp = CGDataProvider(data: jpegData! as CFData)
let cgImage = CGImage(jpegDataProviderSource: dp!, decode: nil, shouldInterpolate: true, intent: .defaultIntent)

因为我怀疑 autorelase 池稍后会释放那些昂贵的对象。

【讨论】:

  • let jpegData = UIImageJPEGRepresentation(images[i].resize(toSize: pageSize)!, 0.8) 这不再适用于 Swift 4.2。
  • 在 Swift 4.2 中,它现在是 images[i].resize(toSize: pageSize)!.jpegData(compressionQuality: 0.8),如文档 developer.apple.com/documentation/uikit/uiimage/… 中所述
  • 我没有找到任何关于 CGRelease 的信息。你能分享一个关于它的例子吗@SachinVsSachin
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-19
  • 2013-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多