views:

314

answers:

1

I wanted to load and display image(.jpg,.png) having large size e.g. 1800x1200 or 2000x1800 (width x height). If I display such large size images (1800x1200 or 2000x1800) in UIImageView, it also consume lot of memory and application is getting crashed. Also as per Apple's documentation (http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIImage_Class/Reference/Reference.html), we should avoid creating UIImage objects that are greater than 1024 x 1024 in size. One solution is to resize image. I have applied logic to resize image using following code.

UIGraphicsBeginImageContext( newSize );
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

This works fine and resizes the image. But when it loads large image in device context to resize, it consume lot of memory for a second and because of it application is crashing. So this approach is not working. Please share if you have better approach to resize without crashing it.

Also in this (http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIImage_Class/Reference/Reference.html) link, Apple said that

"You should avoid creating UIImage objects that are greater than 1024 x 1024 in size. Besides the large amount of memory such an image would consume, you may run into problems when using the image as a texture in OpenGL ES or when drawing the image to a view or layer. This size restriction does not apply if you are performing code-based manipulations, such as resizing an image larger than 1024 x 1024 pixels by drawing it to a bitmap-backed graphics context. In fact, you may need to resize an image in this manner (or break it into several smaller images) in order to draw it to one of your views.". 

Can somebody elaborate more on "This size restriction does not apply if you are performing code-based manipulations, such as resizing an image larger than 1024 x 1024 pixels by drawing it to a bitmap-backed graphics context." ? How to draw image on bitmap-backed graphics context? What is bitmap-backed graphics context? It would help me if somebody can share sample code. Thanks in advance!!

+2  A: 

UIGraphicsBeginImageContext() creates a bitmap-backed graphics context (under the hood it calls CGBitmapContextCreate).

The "restriction" happens because UIViews are rendered using CALayers, and CALayers are rendered as textured polys on the GPU, and the GPU has a maximum texture size (this appears to be 2044 pixels on iPhone 2G/3G and presumably iPod Touch 1G/2G). They've increased it on the 3GS and later devices, presumably because pictures from the camera are bigger.

That said, you ought to be able to manipulate individual camera-sized images without a problem; a crash suggests that you're using a lot of memory elsewhere (possibly a memory leak?).

tc.