Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle large images in iOS

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?

like image 711
lingtianlan Avatar asked Apr 16 '13 17:04

lingtianlan


2 Answers

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.

like image 193
Wain Avatar answered Oct 29 '22 00:10

Wain


Large images don't fit in memory. So loading them into memory to then resize them doesn't work.

To work with very large images you have to tile them. Lots of solutions out there already for example see if this can solve your problem:

https://github.com/dhoerl/PhotoScrollerNetwork

I implemented my own custom solution but that was specific to our environment where we had an image tiler running server side already & I could just request specific tiles of large images (madea server, it's really cool)

The reason tiling works is that basically you only ever keep the visible pixels in memory, and there isn't that many of those. All tiles not currently visible are factored out to the disk cache, or flash memory cache as it were.

like image 40
n13 Avatar answered Oct 28 '22 23:10

n13