My UIView or UIImage is always in blank - iphone

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];

Related

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?

convert uiview to .png image

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();

iPhone : creating Texture2D much slower when image loaded from file in app's Documents, why?

Slower than what? slower than creating the same textures from an image loaded from the app bundle.
How much slower ? 80 times slower on iPhone, similar ratio (but faster overall) on Mac.
My example below shows loading an image with imageNamed: ; creating textures from the first image ; saving image to a file in the app's Documents directory ; loading an image from that file ; creating textures from the second image.
Images are 640x640 png, 100 textures 64x64 are created in each case.
Creation times are 0.51 s vs. 41.3 s.
Can anyone explain this huge difference, and point me to ways and means of speeding up the second case, to make it as fast as the first, if possible ?
Rudif
#import "Texture2D.h"
#define START_TIMER NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];
#define END_TIMER NSTimeInterval stop = [NSDate timeIntervalSinceReferenceDate]; NSLog(#"Time = %f", stop-start);
#interface UIImage (CS_Extensions)
-(UIImage *) imageAtRect:(CGRect)rect;
+(NSString *) documentsDirectory;
+(void) saveImage:(UIImage *)image toDocumentsFile:(NSString *)filename;
+(UIImage *) imageFromDocumentsFile:(NSString *)filename;
+(BOOL) documentsFileExists:(NSString *)filename;
+(void) createTexturesFromImage:(UIImage *)image640x640 texture:(Texture2D **)texture;
#end;
#implementation UIImage (MiscExt)
-(UIImage *)imageAtRect:(CGRect)rect {
CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], rect);
UIImage* subImage = [UIImage imageWithCGImage: imageRef];
CGImageRelease(imageRef);
return subImage;
}
+(NSString *) documentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return documentsDirectory;
}
+(UIImage *) imageFromDocumentsFile:(NSString *)filename {
// NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *documentsDirectory = [self documentsDirectory];
NSString *path = [NSString stringWithFormat:#"%#/%#", documentsDirectory, filename];
NSLog(#"%s : path %#", __FUNCTION__, path);
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
UIImage *image = [[UIImage alloc] initWithData:data];
return image;
}
+(void) saveImage:(UIImage *)image toDocumentsFile:(NSString *)filename {
if (image != nil) { // save to local file
// NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *documentsDirectory = [self documentsDirectory];
NSString *path = [NSString stringWithFormat:#"%#/%#", documentsDirectory, filename];
NSLog(#"%s : path %#", __FUNCTION__, path);
//You can write an NSData to the fs w/ a method on NSData.
//If you have a UIImage, you can do UIImageJPEGRepresentation() or UIImagePNGRepresentation to get data.
NSData *data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
// Check if file exists
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL ok = [fileManager fileExistsAtPath:path];
if (ok) {
NSLog(#"%s : written file %#", __FUNCTION__, path);
}
else {
NSLog(#"%s : failed to write file %#", __FUNCTION__, path);
}
}
}
+(BOOL) documentsFileExists:(NSString *)filename {
NSString *documentsDirectory = [self documentsDirectory];
NSString *path = [documentsDirectory stringByAppendingPathComponent:filename];
NSLog(#"%s : path %#", __FUNCTION__, path);
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:path];
return exists;
}
+(void) createTexturesFromImage:(UIImage *)image640x640 texture:(Texture2D **)texture {
NSLog(#"%s -> ", __FUNCTION__);
START_TIMER;
for (int x = 0; x < 9; ++x) {
for (int y = 0; y < 9; ++y) {
UIImage *ulCorner = [image640x640 imageAtRect:CGRectMake(x*64,y*64,64,64)];
texture[y*10+x] = [[Texture2D alloc] initWithImage:ulCorner];
}
}
END_TIMER;
NSLog(#"%s <- ", __FUNCTION__);
}
#end
-(void) test {
Texture2D *texture1[100];
Texture2D *texture2[100];
// compare texture creation from a bundled file vs Documents file
{
UIImage *imageBundled = [UIImage imageNamed:#"bivio-640x640.png"];
[UIImage createTexturesFromImage:imageBundled texture:texture1];
[UIImage saveImage:imageBundled toDocumentsFile:#"docfile.png"];
BOOL ok = [UIImage documentsFileExists:#"docfile.png"];
UIImage *imageFromFile = [UIImage imageFromDocumentsFile:#"docfile.png"];
[UIImage createTexturesFromImage:imageFromFile texture:texture2];
}
}
When you built your project, XCode optimises PNGs that you put in resources.
This article explains it in details: http://iphonedevelopment.blogspot.com/2008/10/iphone-optimized-pngs.html