简体   繁体   中英

UIImageJPEGRepresentation using large amount of memory (Swift 3.0)

I'm trying to compress and get the NSdata from between 20 and 30 UIImages with a "for-loop" like this:

for theImage in selectedUIImages {

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

}

Tried on an iPhone 7 with no issues besides my app using upto 700MB of memory when going through the loop, but on an older iPhone I get the message:

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

The main objective is to get the NSData from the UIImage so I can put the image in a dir for uploading. Let me explain:

The Amazon S3 Transfer utility wants a path/url to the image and therefore I need to make a path/url for the UIImage and the only way i know is to get it by:

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

Try using an autorelease pool:

autoreleasepool {
    for theImage in selectedUIImages {

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

     }
}

and move it in a background thread.

Because your app run out of memory. You can save it to Document directory after compress then upload it to server one by one. So it not make your memory issue.

You can decrease the image size by decreasing a ratio parameter. You can use 0.3 instead 0.5.

for theImage in selectedUIImages {

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM