UIImage数组到PDF转换内存泄漏

时间:2018-11-20 11:31:08

标签: ios swift pdf memory memory-leaks

我想将UIImage合并到PDF文档中,然后它作为数据发送到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)
    }        
}

1 个答案:

答案 0 :(得分:0)

请尝试对这些对象使用 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)

由于我对自动释放池会在以后释放那些昂贵的对象产生怀疑。