Sunday, 2 June 2013

Using camera to take picture and save that to file: cocos2d

/* Using camera to take a photo */

    // in .h File //
        @interface HelloWorld : CCLayer <UIImagePickerControllerDelegate, UINavigationControllerDelegate>{
   
            UIImagePickerController *uip;
            UIImage *profileImage;
        }

    // in .m File //
        #import "AppDelegate.h"

        -(void)takePhoto{
            AppDelegate *appdel = [UIApplication sharedApplication].delegate;
   
            @try {
       
                uip = [[UIImagePickerController alloc] init] ;
                uip.sourceType = UIImagePickerControllerSourceTypeCamera;
                uip.allowsEditing = YES;
                uip.delegate = self;
            }
            @catch (NSException * e) {
                [uip release];
                uip = nil;
            }
            @finally {
                if(uip) {
                    [appdel.viewController presentModalViewController:uip animated:YES];
                }
            }
        }



    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
   
        profileImage=[info objectForKey:UIImagePickerControllerEditedImage];
        AppDelegate *appdel = [UIApplication sharedApplication].delegate;
        [appdel.viewController dismissModalViewControllerAnimated:YES];
        [uip release];
       
        [NSThread detachNewThreadSelector:@selector(writeImgToPath:) toTarget:self withObject:profileImage]; 
         
       
    }


// To write the image to file //
    -(void)writeImgToPath:(id)sender
    {
       
        NSAutoreleasePool *pool = [NSAutoreleasePool new];
        UIImage *image = sender;
        NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                           NSUserDomainMask,
                                                           YES);
        CGSize size;
        int currentProfileIndex = 1
        NSString *path = [[pathArr objectAtIndex:0]
                      stringByAppendingPathComponent:[NSString stringWithFormat:@"Img_%d.png",currentProfileIndex]];           
       
        size = CGSizeMake(120, 120);
        UIGraphicsBeginImageContext(size);
        [image drawInRect:CGRectMake(0, 0, 120, 120)];
        image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
   
        NSData *data = UIImagePNGRepresentation(image);
        [data writeToFile:path atomically:YES];
        NSLog(@"Saved.....");
       
        CGRect r = CGRectMake(0, 0, 80, 80);
        UIGraphicsBeginImageContext(r.size);
   
        UIImage *img1;
   
        [image drawInRect:r];
        img1 = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
       
        [pool release];
    }

No comments:

Post a Comment