Handle large images in iOS

lingtianlan picture lingtianlan · Apr 16, 2013 · Viewed 7.1k times · Source

I want to allow the user to select a photo, without limiting the size, and then edit it.

My idea is to create a thumbnail of the large photo with the same size as the screen for editing, and then, when the editing is finished, use the large photo to make the same edit that was performed on the thumbnail.

When I use UIGraphicsBeginImageContext to create a thumbnail image, it will cause a memory issue.

I know it's hard to edit the whole large image directly due to hardware limits, so I want to know if there is a way I can downsample the large image to less then 2048*2048 wihout memory issues?

I found that there is a BitmapFactory Class which has an inSampleSize option which can downsample a photo in Android platform. How can this be done on iOS?

Answer

Wain picture Wain · Nov 16, 2013

You need to handle the image loading using UIImage which doesn't actually load the image into memory and then create a bitmap context at the size of the resulting image that you want (so this will be the amount of memory used). Then you need to iterate a number of times drawing tiles from the original image (this is where parts of the image data are loaded into memory) using CGImageCreateWithImageInRect into the destination context using CGContextDrawImage.

See this sample code from Apple.