Capturing the screen and saving it as an image file

Procedure of capturing image of a UIView

  1. Create a Bitmap Context
  2. Get the CALayer object (calayer, for example) through UIView’s layer property
  3. Call CALayer’s renderInContext: with passing the Bitmap Context as the argument, now you got the captured image in the bitmap context
  4. Get a CGImageRef from CGBitmapContextCreateImage( Bitmap Context ) call
  5. Create an UIImage object by calling [UIImage imageWithCGImage: CGImageRef ]
  6. Call UIImagePNGRepresentation( UIImage object) to get a PNG data (NSData * type)
  7. Save the PNG data to a file

To save a JPEG image, call UIImageJPEGRepresentation() instead of UIImagePNGRepresentation()

Data flow:
UIWindow -> CALayer -> Bitmap Context -> CGImageRef -> UIImage -> NSData * -> PNG/JPEG file

Example code:

NSData *imageData = UIImagePNGRepresentation(capturedImage);

if(imageData != nil)


NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsPath = [paths objectAtIndex:0];

NSString *filePath = [documentsPath stringByAppendingPathComponent:@”myfile.png”];

[imageData writeToFile:filePath atomically:YES];


EDIT: The procedure above generates corrupted pixels when there is transparent pixels (not fully opaque, through alpha value). Instead, following piece of code works better and even simpler.

+ (UIImage *) captureImageOfView:(UIView *)srcView



[srcView.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *anImage = UIGraphicsGetImageFromCurrentImageContext();


return anImage;


However, there is report the smilar code capturing image of the UIWindow object, that represents the whole screen, still corrupts some part of the image, according this link:

[self.view.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *anImage = UIGraphicsGetImageFromCurrentImageContext();

So, it is strongly recommended to capture the entire screen using UIGetScreenImage().

Capture screenshot:

CGImageRef cgImg=UIGetScreenImage();
UIImage *scImage=[UIImage imageWithCGImage:cgImg];

Saving image to “Saved Photo” album

Adds the specified image to the user’s Saved Photos album.

void UIImageWriteToSavedPhotosAlbum (
UIImage *image,
id completionTarget,
SEL completionSelector,
void *contextInfo

Leave a Reply