Tuesday 30 December 2014

Downscale Multiple Huge ALAssets without fear of SIGKILL

This post is inspired by http://www.mindsea.com/2012/12/downscaling-huge-alassets-without-fear-of-sigkill/
The post basically focuses on downscaling huge images which are in the form of ALAssets. ALAssets are used when you want to use Asset Library for mirroring or extending the functionality of UIImagePickerController.

I came across the issue where my app was crashing if very large images (>50 MB) were being sent. This was because the dirty memory of the image (uncompressed image loaded in memory) shot up memory usage of the app and hence leading to the app being killed.

The above link in the first line suggests the correct solution for downscaling huge images. This helped when sending one image only, but not multiple images. My app was still crashing if i tried to send multiple large images.
Then i finally figured out that i was dispatching the block on the Global Queue which introduced concurrency and hence multiple image's dirty memory lead to app getting killed.

The solution i implemented is by creating a serial queue when sending multiple images.

dispatch_queue_t serialImageProcessingQueue;
        serialImageProcessingQueue = dispatch_queue_create(kImageProcessingQueueName, NULL);
        
        for(ALAsset *asset in assets) {
            @autoreleasepool {
                dispatch_async(serialImageProcessingQueue, ^{
          //Use the method provided in the link above for creating desired resolution image out of the large image
                    UIImage *image = [ALAsset thumbnailForAsset:asset maxPixelSize:kThread_MaxMediaImageSize];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self sendImage:image saveToLibrary:NO];
                    });
                });
            }
        }
        

        dispatch_release(serialImageProcessingQueue);


If you want to dig deep on what is happening when you try to retrieve a lower resolution image. Refer to 

This link explains in detail how exactly the downsizing happens. The sample code makes for an interesting read. :)
Hope this helps someone...

No comments:

Post a Comment