Tuesday, February 15, 2011

Taking screenshot from an iPhone App


UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *saveImage = UIGraphicsGetImageFromCurrentImageContext();
CGContextRef context = UIGraphicsGetCurrentContext();
UIImageWriteToSavedPhotosAlbum(saveImage, self, @selector(image:didFinishSavingWithError:contextInfo:),  &context);
UIGraphicsEndImageContext();
NSData *imageData = UIImagePNGRepresentation(saveImage);
NSString *imageName = @"temp.png";
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
[imageData writeToFile:fullPathToFile atomically:NO];


 Above code takes screenshot of the view & save this image in the documentsDirectory as "temp.png"

 NSInteger primaryKeyValue = 1;
 NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString* documentsDirectory = [paths objectAtIndex:0];
 NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:@"temp.png"];
 NSString *filePath2 = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat: @"%d.png",primaryKeyValue ]];
 NSFileManager *fileMgr = [NSFileManager defaultManager];
[fileMgr moveItemAtPath:fullPathToFile toPath:filePath2 error:nil];


 Later, if you want to use this image

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
 NSString *uniquePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat: @"%d.png",primaryKeyValue ]]; 
UIImage *image = [UIImage imageWithContentsOfFile:uniquePath]; 



No comments:

Post a Comment