cocos2d Using camera to take picture and save that to file - ios

cocos2d Using camera to take picture and save that to file
I can use camera to take picture.
But this picture is a part of this picture.(a white White border)
How get a big picture?
I want to get a clear picture.
thank you!!
-(void)takePhoto{
AppController *appdel = (AppController*) [[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.navController presentModalViewController:uip animated:YES];
}
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
profileImage=[info objectForKey:UIImagePickerControllerCropRect];
AppController *appdel = (AppController*) [[UIApplication sharedApplication] delegate];
[appdel.navController dismissModalViewControllerAnimated:YES];
[uip release];
[NSThread detachNewThreadSelector:#selector(writeImgToPath:) toTarget:self withObject:profileImage];
}
-(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(1320, 480);
UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0, 0, 1320, 480)];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
NSLog(#”Saved…..”);
CGRect r = CGRectMake(0, 0, 1320, 480);
UIGraphicsBeginImageContext(r.size);
UIImage *img1;
[image drawInRect:r];
img1 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(img1, nil, nil, nil);
[pool release];
}
-(id) init
{
[self takePhoto];
}
return self;
}

Related

Can't Revert Back to Original Image After Using UIImagePickerController

I am having an interesting little problem using the uiimagepickercontroller and was wondering if anyone has any insight as to what might be happening. Users can take pictures with the camera or pick from the photo library until the cows come home as many times in a row as they like. My issue lies in allowing users to revert back to the original image that shipped with the app. Here is the flow:
Users go the the tableview which shows a thumbnail of the image.
Users navigate to the detail view which shows a larger view of the image.
Users can tap on the image in the detail view to bring up a custom alertcontroller with options to a) use the camera to take a picture, b) use a picture from their library, or c) revert back to the original image.
Users choose either option 'a' or option 'b' to either take a picture or use a picture from the photo library. IF they IMMEDIATELY change their mind about using one of those choices and want to just go back to using the original image, nothing happens! They can snap another picture or choose another image right away, but cannot revert back to the original image right away.
Reverting back to the original image DOES work perfectly when the app has been closed and then opened again. Sometimes it will work if you navigate around to other views within the app and then come back to the detail view where they just added their own image. By why the delay? I've searched around for two weeks but have not found anything resembling my problem or any solutions that help in any way (like reloading the headerview where image is sitting). Any thoughts?
Also I have figured out how to save the image to iCloud by using the documentation but cannot figure out how to retrieve them so there is no code for that. That is entirely different question. The same thing seems to occur even without that code.
Thanks for taking the time to look at this!
Here is some code:
-(void)bookImageTapped:(UIGestureRecognizer *)gesture
{
URBAlertView *changeImageAlertView = [[URBAlertView alloc] initWithTitle:#"Add A New Book Cover Image" message:nil cancelButtonTitle:#"Cancel" otherButtonTitles:#"Use Camera", #"Open Gallery", #"Use Original Photo", nil];
[changeImageAlertView setHandlerBlock:^(NSInteger buttonIndex, URBAlertView *alertView) {
[self checkPermission];
if (PHAuthorizationStatusAuthorized)
{
if(buttonIndex == 0)
{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
pickerController.delegate = self;
pickerController.allowsEditing = NO;
pickerController.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentViewController:pickerController animated:YES completion:nil];
}];
[alertView hide];
}
else
{
NSLog(#"Camera not available");
[alertView hide];
}
}
else if (buttonIndex == 1)
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
pickerController.delegate = self;
pickerController.allowsEditing = NO;
pickerController.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:pickerController animated:YES completion:nil];
}];
[alertView hide];
}
else if (buttonIndex == 2)
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self restoreOriginalPhoto];
}];
[alertView hide];
}
else
{
NSLog(#"button 2 cancel");
[alertView hide];
}
}
}];
[changeImageAlertView show];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(nonnull NSDictionary<NSString *,id> *)info
{
[picker dismissViewControllerAnimated:YES completion:nil];
_book.largeBookImage = [info objectForKey:UIImagePickerControllerOriginalImage];
_book.largeBookImage = [self scaleImage:_book.largeBookImage toSize:CGSizeMake(120, 168)];
_bookImageView.image = _book.largeBookImage;
_book.wasNewImageAdded = YES;
_book.originalImageUsed = NO;
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[self saveImage:_book.largeBookImage withFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath
{
if ([[extension lowercaseString] isEqualToString:#"png"])
{
[UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"png"]] options:NSAtomicWrite error:nil];
//Create a URL to the local file
NSURL *resourceURL = [NSURL fileURLWithPath:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"png"]]];
if (resourceURL)
{
CKAsset *asset = [[CKAsset alloc] initWithFileURL:resourceURL];
//create a record object
CKRecord *bookCover = [[CKRecord alloc] initWithRecordType:#"Bookcover"];
//set the record's fields
bookCover[#"title"] = _book.title;
bookCover[#"bookImage"] = asset;
/* TO SAVE A RECORD */
//get the public database
CKContainer *appContainer = [CKContainer defaultContainer];
CKDatabase *publicDatabase = [appContainer publicCloudDatabase];
[publicDatabase saveRecord:bookCover completionHandler:^(CKRecord *bookCover, NSError *error) {
if (error)
{
//insert error handling
return;
}
//insert succesfully saved record code
NSLog(#"png record saved after using picker!");
}];
}
}
else if ([[extension lowercaseString] isEqualToString:#"jpg"] || [[extension lowercaseString] isEqualToString:#"jpeg"])
{
[UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"jpg"]] options:NSAtomicWrite error:nil];
//Create a URL to the local file
NSURL *resourceURL = [NSURL fileURLWithPath:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"jpg"]]];
if (resourceURL)
{
CKAsset *asset = [[CKAsset alloc] initWithFileURL:resourceURL];
//create a record object
CKRecord *bookCover = [[CKRecord alloc] initWithRecordType:#"Bookcover"];
//set the record's fields
bookCover[#"title"] = _book.title;
bookCover[#"bookImage"] = asset;
/* TO SAVE A RECORD */
//get the public database
CKContainer *appContainer = [CKContainer defaultContainer];
CKDatabase *publicDatabase = [appContainer publicCloudDatabase];
[publicDatabase saveRecord:bookCover completionHandler:^(CKRecord *bookCover, NSError *error) {
if (error)
{
//insert error handling
return;
}
//insert succesfully saved record code
NSLog(#"jpg record saved after using picker!");
}];
}
}
else
{
NSLog(#"Image Save Failed\nExtension: (%#) is not recognized, use (PNG/JPG)", extension);
}
}
- (UIImage *) scaleImage:(UIImage*)image toSize:(CGSize)newSize
{
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
-(void)restoreOriginalPhoto
{
NSLog(#"restore photo called");
_book.originalImageUsed = YES;
_book.wasNewImageAdded = NO;
_bookImageView.image = _book.largeBookImage;
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[self saveImage:_book.largeBookImage withFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
}
Here is the headerview with the imageview:
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
_headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 26)];
_headerView.backgroundColor = [UIColor colorWithRed:8/255.0 green:46/255.0 blue:46/255.0 alpha:0.8];
if (section == 0)
{
_headerView.backgroundColor = [UIColor whiteColor];
_bookImageView = [[UIImageView alloc] initWithFrame:CGRectMake((tableView.frame.size.width - 120)/2, 6, 120, 168)];
_bookImageView.contentMode = UIViewContentModeScaleAspectFit;
if (_book.wasNewImageAdded)
{
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage * image = [self loadImageWithFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
_bookImageView.image = image;
}
else
{
_bookImageView.image = _book.largeBookImage;
}
if(_book.originalImageUsed)
{
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage * image = [self loadImageWithFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
_bookImageView.image = image;
}
UITapGestureRecognizer *bookImageTouched = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(bookImageTapped:)];
bookImageTouched.numberOfTapsRequired = 1;
[_bookImageView addGestureRecognizer:bookImageTouched];
_bookImageView.userInteractionEnabled = YES;
[_headerView addSubview:_bookImageView];
}
I finally figured it out! It seems that I was confusing xcode with my property names. The code ended up much simpler in the end.
In didFinishPickingMediaWithInfo I created a UIImage and then set it to the bookImageView.image. Later, when I wanted to be able to update the image back to the original image, then I could call the bundle asset, _book.largeBookImage. Voila! The image was able to update immediately.
The most pertinent code is posted below.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(nonnull NSDictionary<NSString *,id> *)info
{
[picker dismissViewControllerAnimated:YES completion:nil];
_chosenImage = [[UIImage alloc] init];
_chosenImage = [info objectForKey:UIImagePickerControllerOriginalImage];
_bookImageView.image = _chosenImage;
_book.wasNewImageAdded = YES;
_book.originalImageUsed = NO;
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[self saveImage:_chosenImage withFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
}
-(void)saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath
{
if ([[extension lowercaseString] isEqualToString:#"png"])
{
[UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"png"]] options:NSAtomicWrite error:nil];
[self.tableView reloadData];
}
else if ([[extension lowercaseString] isEqualToString:#"jpg"] || [[extension lowercaseString] isEqualToString:#"jpeg"])
{
[UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"jpg"]] options:NSAtomicWrite error:nil];
[self.tableView reloadData];
}
else
{
//NSLog(#"Image Save Failed\nExtension: (%#) is not recognized, use (PNG/JPG)", extension);
}
}
-(void)restoreOriginalPhoto
{
_book.originalImageUsed = YES;
_book.wasNewImageAdded = NO;
_bookImageView.image = _book.largeBookImage;
_backgroundImage.image = _book.largeBookImage;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
if (section == 0)
{
_bookImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 120, 168)];
_bookImageView.contentMode = UIViewContentModeScaleAspectFit;
_bookImageView.clipsToBounds = YES;
_bookImageView.layer.cornerRadius = 10.0f;
if (_book.wasNewImageAdded)
{
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage * image = [self loadImageWithFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
_bookImageView.image = image;
}
else
{
_bookImageView.image = _book.largeBookImage;
}
if(_book.originalImageUsed)
{
_bookImageView.image = _book.largeBookImage;
}
}
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if(_book.originalImageUsed)
{
_bookImageView.image = _book.largeBookImage;
}
[self.tableView reloadData];
[self.tableView setContentOffset:CGPointZero animated:NO];
}

iOS Creating video from images and get EXC_BAD_ACCESS for second try

I'm making an app what makes video from images.
Here I make a new array:
self.imageList = [NSMutableArray<UIImage *> new];
And then add lots of images to this array.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
for (NSString *framePath in _effect.framePathList)
{
#autoreleasepool
{
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,framePath];
UIImage *frame = [[UIImage alloc] initWithContentsOfFile:filePath];
i++;
self.selectedEffect.image = [self applyEffect:frame];
CGRect rect = [_backgroundView bounds];
UIGraphicsBeginImageContextWithOptions(rect.size,NO,0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
[self.backgroundView.layer renderInContext:context];
UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
if (capturedImage.scale * capturedImage.size.height > 640)
{
CGSize newSize = CGSizeMake(640, 640);
UIGraphicsBeginImageContext(newSize);
[capturedImage drawInRect:CGRectMake(0, 0, newSize.height, newSize.height)];
UIImage *destImage = UIGraphicsGetImageFromCurrentImageContext();
capturedImage = destImage;
destImage = nil;
UIGraphicsEndImageContext();
}
dispatch_sync(dispatch_get_main_queue(), ^
{
if (self.updateLoadingState)
{
self.updateLoadingState((float)i / framaCount * 100.0);
}
});
if (capturedImage)
{
[_imageList addObject:capturedImage];
}
}
}
Then try to create the video. Here are the methods
[self.movieMaker createMovieFromImages:_imageList withCompletion:^(NSURL *fileURL)
{
{
if (_finishBlock)
{
_finishBlock();
}
}
}];
This method is in the movieMaker class.
- (void) createMovieFromSource:(NSArray *)images extractor:(CEMovieMakerUIImageExtractor)extractor withCompletion:(CEMovieMakerCompletion)completion {self.completionBlock = completion;
[self.assetWriter startWriting];
[self.assetWriter startSessionAtSourceTime:kCMTimeZero];
dispatch_queue_t mediaInputQueue = dispatch_queue_create("mediaInputQueue", NULL);
__block NSInteger i = 0;
NSInteger frameNumber = [images count];
[self.writerInput requestMediaDataWhenReadyOnQueue:mediaInputQueue usingBlock:^{
while (YES)
{
#autoreleasepool
{
if (i >= frameNumber)
{
break;
}
if ([self.writerInput isReadyForMoreMediaData])
{
CVPixelBufferRef sampleBuffer;
NSMutableArray *test = [NSMutableArray arrayWithArray:images];
UIImage *img = extractor([test objectAtIndex:i]);
if (img == nil) {
i++;
NSLog(#"Warning: could not extract one of the frames");
continue;
}
CGImageRef img2 = [img CGImage];
sampleBuffer = [self newPixelBufferFromCGImage:img2];
CGImageRelease(img2);
if (sampleBuffer) {
if (i == 0)
{
[self.bufferAdapter appendPixelBuffer:sampleBuffer withPresentationTime:kCMTimeZero];
}
else
{
CMTime lastTime = CMTimeMake(i-1, self.frameTime.timescale);
CMTime presentTime = CMTimeAdd(lastTime, self.frameTime);
[self.bufferAdapter appendPixelBuffer:sampleBuffer withPresentationTime:presentTime];
}
CFRelease(sampleBuffer);
i++;
}
}
}
}
[self.writerInput markAsFinished];
[self.assetWriter finishWritingWithCompletionHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
self.completionBlock(self.fileURL);
});
}];
CVPixelBufferPoolRelease(self.bufferAdapter.pixelBufferPool);
}];
}
Without the CGImageRelease(img2); everything working but I have a huge memory leak. I have more then 100 images in the array. If I use CGImageRelease(img2); the first run is ok no memory leak. But If I try it again I get EXC_BAD_ACCESS in this line: self.imageList = [NSMutableArray<UIImage *> new];
Here is the error
What can I do? Thanks in advance!

Adding zoom in/out and crop for photo

I am trying to add capability to zoom in/out and crop a profile image before saving change but I am not sure how to go about this. Here below are my relevant codes:
- (void)viewDidLoad {
...
NSString *urlString = [User sharedUser].avatar;
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
[_avatarImageView setImageWithURLRequest:imageRequest placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
_avatarImageView.image = image;
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(#"Error: %#", error);
}];
_avatarImageView.layer.masksToBounds = YES;
_avatarImageView.layer.cornerRadius = _avatarImageView.frame.size.width / 2; //create circle image
[self initImagePicker];
...
}
- (void) initImagePicker {
myPicker = [[MyImagePicker alloc] init];
myPicker.SourceVC = self;
myPicker.SourceView = self.view;
myPicker.delegate = self;
myPicker.isImage = YES;
[myPicker initImagePicker];
}
- (IBAction) ChooseImageSourceAlbum {
tempType = POPUP_TYPE_IMAGPICKER;
selectArray = #[#"Camera",#"Choose Photos",#"Delete Photo"];
//Call popup
PopupTemplateViewController *vc = [[PopupTemplateViewController alloc] initWithNibName:#"PopupTemplateViewController" bundle:nil];
vc.delegate = self;
vc.dataArray = selectArray;
vc.type = POPUP_TYPE_OTHERS;
self.useBlurForPopup = NO;
[self presentPopupViewController:vc animated:YES completion:nil];
}
- (void) MyImagePickerTakePicture:(NSDictionary *)_dic {
NSString *mediaType = [_dic objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:#"public.image"]) {
UIImage *image = [_dic objectForKey:UIImagePickerControllerOriginalImage];
//??? add crop and zoom image here!!!
[self performSelector:#selector(processImage:) withObject:image afterDelay:0.25f];
}
}
- ( void )processImage:( UIImage * )image {
CGFloat ratio = 1.0;
if (image.size.width > 400) {
ratio = 400 / image.size.width;
}
else if (image.size.height > 600) {
ratio = 600 / image.size.height;
}
UIImage *imageResize = [self scaleImage:image toScale:ratio];
[_avatarImageView setImage:imageResize];
[self UpdateAvatar];
}
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize{
UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
[image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
- (void) UpdateAvatar {
[self showSeachingPopViewinView:self.view type:POPUP_TYPE_UPDATE];
NSString *account = [[User sharedUser] account];
NSMutableDictionary *parameters = [NSMutableDictionary new];
[parameters setObject:account forKey:#"account"];
[parameters setObject:_avatarImageView.image forKey:#"avatar"];
[GatewayManager callUpdateAvatar:parameters delegate:self];
}
- (void)popupView:(PopupTemplateViewController *)popupView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self dismissPopupViewControllerAnimated:NO completion:nil];
NSString *str = selectArray[indexPath.row];
if ([str isEqualToString:#"Camera"]) {
[myPicker OpenCamera];
}
else if ([str isEqualToString:#"Choose Photos"]) {
[myPicker OpenAlbum];
} else {
[self deletePhoto];
}
}
Now when I tab the profile image it will pop up view showing 3 choices: Camera, Choose Photo, Delete Photo. What I want to achieve is that after taking a photo or choosing a photo I want to have another view with the photo that I can zoom in/out and crop. Thanks in advance.
I found a property of image picker that allows editing, so I added this in init image picker:
imagePicker.allowsEditing = YES; //allows image to be editted before choosing
Also in MyImagePickerTakePicture I changed UIImagePickerControllerOriginalImage to UIImagePickerControllerEditedImage
- (void) MyImagePickerTakePicture:(NSDictionary *)_dic {
NSString *mediaType = [_dic objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:#"public.image"]) {
UIImage *image = [_dic objectForKey:UIImagePickerControllerOriginalImage];
//??? add crop and zoom image here!!!
[self performSelector:#selector(processImage:) withObject:image afterDelay:0.25f];
}
}

How to Multiple UIImages cropping and saving in a single loop

In my project is using maximum 60 images and One of my feature is needs to be an automatically crop all the 60 images in a given Ratio. I'm using the for loop for this implementation.
Inside the for loop contains crop and save the images. It was Implemented. But My app Meets crash in device because of Due to Memory pressure. Please Help Me
for (int ref=0; ref<[_selectedPhotosCollectionthumb count];ref++)
{
UIScrollView *scrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(0,biManager.screenSize.height/2,biManager.screenSize.width,biManager.screenSize.height/2)];
[scrollView setDelegate:self];
[scrollView setBackgroundColor:[UIColor clearColor]];
[self addSubview:scrollView];
// scrollView.backgroundColor=[UIColor blueColor];
scrollView.userInteractionEnabled=YES;
scrollView.scrollEnabled=YES;
scrollView.tag=ref;
scrollView.hidden=YES;
[_scrollViews addObject:scrollView];
NSLog(#"%i",[_selectedPhotosCollection count]);
NSMutableArray *arrayCell=[_productCollectionsDict valueForKey:[_selectedPhotosCollection objectAtIndex:ref]];
int heightV=0;
for (int cellIndex=0;cellIndex<[arrayCell count];cellIndex++)
{
PrintCellView *cellObj=[arrayCell objectAtIndex:cellIndex];
if(cellObj.pCount>0)
{
PrintEditCellView *cell;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
cell=[[PrintEditCellView alloc] initWithFrame:CGRectMake(0,heightV*100,biManager.screenSize.width,100)];
scrollView.contentSize=CGSizeMake(0,heightV*100+100);
cell.delegate=self;
}
else
{
cell=[[PrintEditCellView alloc] initWithFrame:CGRectMake(0,heightV*50,biManager.screenSize.width,50)];
scrollView.contentSize=CGSizeMake(0,heightV*50+50);
cell.delegate=self;
}
NSDate *now = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"hh:mm:ss";
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSLog(#"The Current Time is %#",[dateFormatter stringFromDate:now]);
// NSData *imageData=UIImageJPEGRepresentation(Thumbimage,1.0);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:[_selectedPhotosCollection objectAtIndex:ref]];
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:path];
UIImage *image1=[[UIImage alloc]initWithData:data];
cell.productName.text=cellObj.productName.text;
UIImage * image=[self imageByCropping:image1 CropRatio:cell.productName.text];
NSLog(#"CROPPPP");
NSData *imageData= [[NSData alloc] initWithData:UIImageJPEGRepresentation(image,1.0)];
//
NSString* path1 = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"Prydex%i%#.jpg",cellIndex,[dateFormatter stringFromDate:now]]];
NSLog(#"pthhh:%#",path1);
[imageData writeToFile:path1 atomically:YES];
cell.editedImageURL=path1;
NSLog(#"%#,%i",cellObj.productName.text,cellObj.pCount);
[scrollView addSubview:cell];
[cell release];
heightV=heightV+1;
[dateFormatter release];
[image1 release];
// [imageData release];
// [image release];
}
}
//NSLog(#"Scroll Count %i",[_scrollViews count]);
for (UIScrollView *scrollView in _scrollViews)
{
if (scrollView.tag==0)
{
scrollView.hidden=NO;
}
else
{
scrollView.hidden=YES;
}
}
[SVProgressHUD dismiss];
}
Cropping Code
- (UIImage *)imageByCropping:(UIImage *)image CropRatio:(NSString*)ratio
{
CGSize size;
NSArray *array=[ratio componentsSeparatedByString:#"*"];
NSString *productWidth=[array objectAtIndex:0];
NSString *productHeight=[array objectAtIndex:1];
NSLog(#"SIZE:%#,%#",productWidth,productHeight);
NSLog(#"SIZE:%f,%f",image.size.width,image.size.height);
if (image.size.width/[productWidth intValue]>=230)
{
if (image.size.height/[productHeight intValue]>=230) {
size=CGSizeMake([productWidth intValue]*230,[productHeight intValue]*230);
NSLog(#"SIZE Inner:%i,%i",[productWidth intValue],[productHeight intValue]);
}
else if(image.size.width/[productWidth intValue]>=100)
{
if (image.size.height/[productHeight intValue]>=100)
{
size=CGSizeMake([productWidth intValue]*100,[productHeight intValue]*100);
NSLog(#"SIZE outer:%i,%i",[productWidth intValue],[productHeight intValue] );
}
}
}
else if(image.size.width/[productWidth intValue]>=100)
{
if (image.size.height/[productHeight intValue]>=100)
{
size=CGSizeMake([productWidth intValue]*100,[productHeight intValue]*100);
NSLog(#"SIZE outer:%i,%i",[productWidth intValue],[productHeight intValue] );
}
}
NSLog(#"crop---->%#",NSStringFromCGSize(size));
double x = (image.size.width - size.width) / 2.0;
double y = (image.size.height - size.height) / 2.0;
CGRect cropRect = CGRectMake(x, y, size.width, size.height);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return cropped;
}
The solution might be using recursion:
Create a method that takes an array of images you need to process. Inside the method check if array count is zero.
If it is empty you should return, possibly doing some callback to notify the application your image processing is done.
If the array is not empty, take the first image from the array, do all the processing, then remove the first object from the array and call the same method with the new array missing that element. The call should be kind of
[self performSelector:#selector(methodName:) withObject:imageArray];
All together should look something like this:
- (void)processImages:(NSArray *)images {
if(images.count < 1) {
[self performSelectorOnMainThread:#selector(imageProcessingDone) withObject:nil waitUntilDone:NO];
}
else {
UIImage *toProcess = images[0];
NSMutableArray *newArray = [images mutableCopy];
[newArray removeObjectAtIndex:0];
//do the processing
[self performSelector:#selector(processImages:) withObject:newArray];
}
}

Can't Capture Full Screen of iCarousel

I have a problem to capture full screen of iCarousel. it can capture only index of Carousel only .
UIGraphicsBeginImageContext(caputureView.bounds.size);
[caputureView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Try something like this:
- (void) getFullScreenScreenShot
{
AppDelegate* appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
UIView* superView = appDelegate.viewController.view;
CGRect fullScreenFrame = superView.frame;
UIGraphicsBeginImageContextWithOptions(fullScreenFrame.size, YES, 0.0f);
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0.0f, 0.0f);
[superView.layer renderInContext: UIGraphicsGetCurrentContext()];
UIImageView* screenShot = [[UIImageView alloc] initWithImage: UIGraphicsGetImageFromCurrentImageContext()];
UIGraphicsEndImageContext();
NSData* imageData = UIImageJPEGRepresentation(screenShot.image, 1.0);
NSString* previewFileNamePath = [[CPFileManager documentsPath] stringByAppendingString: #"image.jpg"];
if ([imageData writeToFile: previewFileNamePath
atomically: NO])
{
NSLog(#"See filename:%#", previewFileNamePath);
}
else
{
NSLog(#"Error: %#", previewFileNamePath);
}
}

Resources