convert uiview to .png image - iphone

I am working on iphone and I take the subclass of UIView and in draw rect method I am making some design. I want to convert this view in .png format.
Thanks in advance.

UIGraphicsBeginImageContext(myView.frame.size);
[myView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *data=UIImagePNGRepresentation(viewImage);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *strPath = [documentsDirectory stringByAppendingPathComponent:#"myimage.png"];
[data writeToFile:strPath atomically:YES];

UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)])
UIGraphicsBeginImageContextWithOptions(YourView.frame.size, NO, [UIScreen mainScreen].scale);
else
UIGraphicsBeginImageContext(keyWindow.bounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[keyWindow.layer renderInContext:context];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil);
UIGraphicsEndImageContext();

Related

UIImage Saving issue in iOS7 : Blending issue

Here is screenshot from simulator and saved image:
Code :
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenshotImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//guru - just for simulator
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Image.png"];
[UIImagePNGRepresentation(screenshotImage) writeToFile:filePath atomically:YES];
//end guru
UIImageWriteToSavedPhotosAlbum(screenshotImage, nil, nil, nil);
How can I fix this problem ? Works good when I build it with Xcode4_iOS6, but not with Xcode5_iOS7.
You can fix it in this way:
if([self IS_IOS_7])
{
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, TRUE, [[UIScreen mainScreen] scale]);
}
else
{
UIGraphicsBeginImageContext(self.view.bounds.size);
}
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenshotImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(screenshotImage, nil, nil, nil);
iOS7 Check:
-(bool)IS_IOS_7
{
NSString *currOsVersion = [[UIDevice currentDevice] systemVersion];
float sysver = [currOsVersion floatValue] ;
if(sysver >=7.0f)
return true;
return false;
}

Howe to capture UIView top UIView

i have UIView which displays the Graph..now I need to capture it to the UIImage and I googled it and got the below code.but if i use this in my code its not work.even if I use breakpoint compiler does not reach to this.I am using this in my UIView .where I am going wrong?
+ (UIImage *) imageWithView:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
You can take a screenshot of any view or whole screen of the iPhone app with below method
- (UIImage *)captureView {
//hide controls if needed
CGRect rect = [self.view bounds];
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[self.view.layer renderInContext:context];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
And call it like bellow...
UIImage *tempImageSave=[self captureView];
and you can also save this image with this bellow line for photo album..
UIImageWriteToSavedPhotosAlbum(tempImageSave,nil,nil,nil);
and you can also save this image with this bellow line for Document Directory..
NSData *imageData = UIImagePNGRepresentation(tempImageSave);
NSFileManager *fileMan = [NSFileManager defaultManager];
NSString *fileName = [NSString stringWithFormat:#"%d.png",1];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
[fileMan createFileAtPath:pdfFileName contents:imageData attributes:nil];
If the view contains the layer images or some graphics related data then use below method.
-(UIImage *)convertViewToImage:(UIView *)viewTemp
{
UIGraphicsBeginImageContext(viewTemp.bounds.size);
[viewTemp drawViewHierarchyInRect:viewTemp.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
And use this method like below.
UIImage *tempImageSave = [self convertViewToImage:yourView];
I hope this helpful for you.
Try with this code it may be help you
- (UIImage *)captureView:(UIView *)view {
CGRect screenRect = [[UIScreen mainScreen] bounds];
UIGraphicsBeginImageContext(screenRect.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[[UIColor clearColor] set];
CGContextFillRect(ctx, screenRect);
[view.layer renderInContext:ctx];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
you can save image of View like this way and store image in to Document Directory:-
-(void)SaveViewAsImage
{
UIGraphicsBeginImageContext(self.view.bounds.size);
UIImage *saveImage = UIGraphicsGetImageFromCurrentImageContext();
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIGraphicsEndImageContext();
NSData *imageData = UIImagePNGRepresentation(saveImage);
NSFileManager *fileMan = [NSFileManager defaultManager];
NSString *fileName = [NSString stringWithFormat:#"%d.png",1];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
[fileMan createFileAtPath:pdfFileName contents:imageData attributes:nil];
}
Your image save in Document Directory :)
Download this demo
http://www.sendspace.com/file/gjxa82

Save one page of UIScrollView to image

I have an UIWebView. After loading data to UIWebView, my UIWebView can scroll horizontally, and i enable paging for my scrollView in web view.
My question is:
is there any way to save a page in scrollView in UIWebView to image? I mean, i will get 5 images for 5 pages of scrollView(content size = 5 pages)
you can save your screen like this way:-
-(IBAction)savebutn:(id)sender
{
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *saveImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImagePNGRepresentation(saveImage);
NSFileManager *fileMan = [NSFileManager defaultManager];
NSString *fileName = [NSString stringWithFormat:#"%d.png",imagename];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
[fileMan createFileAtPath:pdfFileName contents:imageData attributes:nil];
}
your Image will be save in your document directory with .png extension
This Code Useful when user want to capture current view ScreenShot and share or save this image....
- (UIImage *)captureView {
//hide controls if needed
CGRect rect = [self.view bounds];
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[self.view.layer renderInContext:context];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
see my blog,... http://parasjoshi3.blogspot.in/2012/06/captureimagescreenshot-of-view.html
:)
CGRect rect = [webview bounds];
UIGraphicsBeginImageContextWithOptions(rect.size,YES,0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
[webview.layer renderInContext:context];
UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
This helps to capture the current image

Lag in UITableView scroll when image is loaded from document directory

I have a UITableView which shows Items with images and their name. The problem is that the scroll's lagging because of the loading of the images for each cell.
This is how I am saving the images captured from the iPhone Camera and resized to 320 by 480.
- (void)saveImage: (UIImage*)image{
if (image != nil)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imageName = [NSString stringWithFormat: #"image_%#.png",[NSDate date]];
item.imageName = imageName;
NSString* path = [documentsDirectory stringByAppendingPathComponent:
imageName];
NSLog(#"%#",path);
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setInteger:[image imageOrientation] forKey:#"kImageOrientation"];
} }
This is how I am resizing it
- (UIImage *)resizeImage:(UIImage*)image newSize:(CGSize)newSize {
CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));
CGImageRef imageRef = image.CGImage;
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
// Set the quality level to use when rescaling
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height);
CGContextConcatCTM(context, flipVertical);
// Draw into the context; this scales the image
CGContextDrawImage(context, newRect, imageRef);
// Get the resized image from the context and a UIImage
CGImageRef newImageRef = CGBitmapContextCreateImage(context);
UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
CGImageRelease(newImageRef);
UIGraphicsEndImageContext();
return newImage;}
And this is how I am loading them in cellForRowAtIndexPath
- (UIImage*)loadImage:(NSString *) imageName{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithString: imageName]];
UIImage* image = [UIImage imageWithContentsOfFile:path];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
UIImage *orientedImage= [UIImage imageWithCGImage: image.CGImage scale:1.0 orientation: [userDefaults integerForKey:#"kImageOrientation"]];
return orientedImage;}
One approach I was thinking of is to have an NSMutableArray with the UIImages loaded in it once and then fetching the images from there. The problem with that approach is that not all cells will have images so say there are 10 cells but only three images in the last 3 cells, the NSMutableArray approach will be a problem here because the images added will be at the indices 0,1,2.
I have one more solution in my mind which I would like to highlight here for you experts to verify if it will work. I actually am using CoreData and have generated the Model for the Item. If I was to manually add a UIImage field in this class and save the image to them objects, will that work or would it be wrong to do that?

My UIView or UIImage is always in blank

I'm trying to take a picture from my UIView, namely I make a screenshot from my UIView but always the UIImage is in blank and I don't know why. And I tested with my iPhone and take a picture in blank. :(
I put #import <QuartzCore/QuartzCore.h> and added QuartzCore.framework.
Could someone help me?
Here is my code:
- (IBAction)savePhoto:(id)sender
{
UIImage *imageCaptured = [self imageFromView:self.view];
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/Test.png"];
// Write a UIImage to JPEG with minimum compression (best quality)
[UIImagePNGRepresentation(imageCaptured) writeToFile:pngPath atomically:YES];
// Let's check to see if files were successfully written...
// Create file manager
NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];
// Point to Document directory
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
// Write out the contents of home directory to console
NSLog(#"Documents directory: %#", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
}
- (UIImage *) imageFromView:(UIView *)view
{
UIGraphicsBeginImageContext(CGSizeMake(320,372));
CGContextRef context = UIGraphicsGetCurrentContext();
[view.layer drawInContext:context];
UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[imageView setImage:screenShot];
return screenShot;
}
Try changing your line of
[view.layer drawInContext:context];
to
[view.layer renderInContext:context];