【问题标题】:UIImageJPEGRepresentation using large amount of memory (Swift 3.0)UIImageJPEGRepresentation 使用大量内存(Swift 3.0)
【发布时间】:2017-02-21 09:10:17
【问题描述】:

我正在尝试使用这样的“for-loop”从 20 到 30 个 UIImage 压缩和获取 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)

【问题讨论】:

  • 你在设备上试过了吗?
  • 普里亚尔:你是什么意思?
  • Martin:这是 swift 3.0
  • @NSNoob 谢谢询问队友 :-) 让我解释一下。 Amazon S3 Transfer 实用程序需要图像的路径/url,因此我需要为 UIimage 创建一个路径/url,我知道的唯一方法是通过以下方式获取它:data.write(to: URL(fileURLWithPath: localPath) , 选项:.atomic)

标签: ios swift xcode swift3


【解决方案1】:

尝试使用自动释放池:

autoreleasepool {
    for theImage in selectedUIImages {

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

     }
}

并在后台线程中移动它。

【讨论】:

  • 将自动释放池放在循环内不是更好吗?
【解决方案2】:

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

【讨论】:

  • 所以最好先压缩再上传。所以基本上 1. 一个压缩的 for 循环,然后是另一个上传的循环?
【解决方案3】:

您可以通过减小比率参数来减小图像大小。您可以使用 0.3 而不是 0.5。

for theImage in selectedUIImages {

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

}

【讨论】:

  • 与以前相同的错误 :( 来自调试器的消息:由于内存问题而终止。
  • @fayyaz 您将不断收到该消息,因为您无法控制 selectedUIImages 数组中的图像数量。它可能适用于多张图片,然后在多一张图片上开始崩溃。
猜你喜欢
  • 2013-12-13
  • 2020-06-19
  • 2011-02-08
  • 1970-01-01
  • 1970-01-01
  • 2017-05-11
  • 1970-01-01
  • 1970-01-01
  • 2016-06-12
相关资源
最近更新 更多