使用大量内存的UIImageJPEGRepresentation(Swift 3.0)

时间:2017-02-21 09:10:17

标签: ios swift xcode swift3

我正在尝试使用这样的“for-loop”压缩并从20到30个UIImages中获取NSdata:

for theImage in selectedUIImages {

let data = UIImageJPEGRepresentation(image,0.5)
// doing something with the data

}

尝试使用iPhone 7,除了我的应用程序时没有问题,在循环中使用高达700MB的内存,但在较旧的iPhone上,我收到消息:

*Message from debugger: Terminated due to memory issue.*

主要目标是从UIImage获取NSData,这样我就可以将图像放在目录中进行上传。让我解释一下:

Amazon S3 Transfer实用程序想要一个路径/ url到图像,因此我需要为UIImage创建一个路径/ url,我知道的唯一方法是通过它:

data.write(to: URL(fileURLWithPath: localPath), options: .atomic)

3 个答案:

答案 0 :(得分:1)

尝试使用自动释放池:

autoreleasepool {
    for theImage in selectedUIImages {

        let data = UIImageJPEGRepresentation(image,0.5)
        // doing something with the data

     }
}

并在后台线程中移动它。

答案 1 :(得分:0)

因为您的应用内存不足。 压缩后可以将其保存到Document目录,然后逐个上传到服务器。所以它不会让你的记忆问题。

答案 2 :(得分:0)

您可以通过减小比率参数来缩小图像尺寸。您可以使用0.3代替0.5。

for theImage in selectedUIImages {

let data = UIImageJPEGRepresentation(image,0.3)
// doing something with the data

}