Capturing the screen and saving it as an image file
Procedure of capturing image of a UIView
Create a Bitmap Context
Get the CALayer object (calayer, for example) through UIView’s layer property
Call CALayer’s renderInContext: with passing the Bitmap Context as the argument, now you got the captured image in the bitmap context
Get a CGImageRef from CGBitmapContextCreateImage( Bitmap Context ) call
Create an UIImage object by calling [UIImage imageWithCGImage: CGImageRef ]
Call UIImagePNGRepresentation( UIImage object) to get a PNG data (NSData * type)
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
{
UIGraphicsBeginImageContext(srcView.bounds.size);
[srcView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *anImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
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: http://stackoverflow.com/questions/1902741/captured-uiview-image-has-distorted-colors-iphone-sdk
UIGraphicsBeginImageContext(self.view.window.frame.size);
[self.view.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *anImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
So, it is strongly recommended to capture the entire screen using UIGetScreenImage().
Capture screenshot:
CGImageRef cgImg=UIGetScreenImage();
UIImage *scImage=[UIImage imageWithCGImage:cgImg];
CFRelease(cgImg);
Saving image to “Saved Photo” album
UIImageWriteToSavedPhotosAlbum
Adds the specified image to the user’s Saved Photos album.
void UIImageWriteToSavedPhotosAlbum (
UIImage *image,
id completionTarget,
SEL completionSelector,
void *contextInfo
);
Discover more from CODE t!ps
Subscribe to get the latest posts sent to your email.