Adding zoom in/out and crop for photo - ios

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

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

Connection interrupted error when loading image from disk using SDWebImage in iOS

I get this error when loading multi images from disk. I used SDWebImage to load image but still get this error then app crashed. I dont know what this error is. Pls give me adivse. Thanks much.
Communications error: <OS_xpc_error: <error: 0x322eb614> { count = 1, contents =
"XPCErrorDescription" => <string: 0x322eb86c> { length = 22, contents = "Connection interrupted" }
}>
Here is the code I used to create the list thumbnail for scrollview
-(void) createPropertyThumbnails:(NSArray*) array
{
int xCoord=10;
int yCoord=7;
int buffer = 7;
for (int pos = 0; pos < array.count; pos++) {
// CREATE VIEW CONTAINS UIIMAGEVIEW HERE
ThumbnailView* thumbnaiCell = [[humbnailView alloc] initWithFrame:CGRectMake(xCoord, yCoord,THUMBNAIL_WIDTH , THUMBNAIL_HEIGHT) andURLImage:array[pos]];
thumbnaiCell.delegate = self;
//set selected for 1st item
if(pos ==0)
{
_selectedCell =thumbnaiCell;
[_selectedCell setSelectedCell:YES];
}
xCoord = xCoord + THUMBNAIL_WIDTH + buffer;
[self.thumbnailScrollView addSubview:thumbnaiCell];
}
[self.thumbnailScrollView setContentSize:CGSizeMake(xCoord, self.thumbnailScrollView.frame.size.height)];
}
- (id)initWithFrame:(CGRect)frame andURLImage:(NSString*) url
{
self = [super initWithFrame:frame];
if (self) {
[self setupProjectThumbnail:frame andURLImage:url];
}
return self;
}
-(void) setupProjectThumbnail:(CGRect) frame andURLImage:(NSString*) url
{
//create load image from cache
NSString *filePath = [[NSBundle mainBundle] pathForResource:url ofType:nil];
NSURL *ImageURL = [NSURL fileURLWithPath:filePath];
if (ImageURL) {
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadImageWithURL:ImageURL
options:0
progress:^(NSInteger receivedSize, NSInteger expectedSize) {
// progression tracking code
}
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
if (image) {
// do something with image
// imageview
UIImageView* imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, frame.size.width, frame.size.height)];
imageview.contentMode = UIViewContentModeScaleToFill;
[self addSubview:imageview];
}
}];
}
}

How to display images as uitableviewcell in ios quickblox chat app?

I am using a custom tableview cell that displays text in chat bubbles and its working fine.
But i want to display images in chat.
For that i am doing belowed steps:
TO choose and upload file:
- (IBAction)btnAttachments:(id)sender{
self.imagePicker = [[UIImagePickerController alloc] init];
self.imagePicker.allowsEditing = NO;
self.imagePicker.delegate = self;
self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:self.imagePicker animated:YES completion:nil];}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage *imgChosen = info[UIImagePickerControllerOriginalImage];
imgChat = imgChosen;
[picker dismissViewControllerAnimated:YES completion:NULL];
// Upload new avatar to Content module
NSData *avatar = [[NSData alloc] initWithData:UIImagePNGRepresentation(imgChat)];
//
//[QBContent TUploadFile:avatar fileName:#"MyAvatar" contentType:#"image/png" isPublic:NO delegate:self];
[QBContent TUploadFile:avatar fileName:#"userChat" contentType:#"image/png" isPublic:YES delegate:self];}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[picker dismissViewControllerAnimated:YES completion:NULL];
}
in Completed with result:
if(result.success && [result isKindOfClass:[QBCFileUploadTaskResult class]])
{
QBCFileUploadTaskResult *res = (QBCFileUploadTaskResult *)result;
NSUInteger uploadedFileID = res.uploadedBlob.ID;
QBChatMessage *message = [[QBChatMessage alloc] init];
message.recipientID = self.opponent.ID;
NSMutableDictionary *msgDict = [[NSMutableDictionary alloc]init];
[msgDict setValue:[NSNumber numberWithInt:uploadedFileID] forKey:#"fileID"];
message.customParameters = msgDict;
[[QBChat instance] sendMessage:message];
}
To download file:
- (void)chatDidReceiveMessageNotification:(NSNotification *)notification{
QBChatMessage *message = notification.userInfo[kMessage];
if(message.customParameters != nil)
{
NSUInteger fileID = [message.customParameters[#"fileID"] integerValue];
// download file by ID
[QBContent TDownloadFileWithBlobID:fileID delegate:self];
}
in completed with result:
if(result.success && [result isKindOfClass:[QBCFileDownloadTaskResult class]])
{
QBCFileDownloadTaskResult *res = (QBCFileDownloadTaskResult *)result;
if ([res file])
{
UIImageView* imageView = [[UIImageView alloc] initWithImage:
[UIImage imageWithData:[res file]]];
[self.messages addObject:imageView];
[self.tblObj reloadData];
}
}
Now, How to display that downloaded image in my chat?
Instruct me about the custom cell which will be used for displaying images.

cocos2d Using camera to take picture and save that to file

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

why can't I access iPad photos library?

I'm using IImagePickerController to get photos from the photo library. Works great on the iphone, but won't work on an iPad. There were solutions suggested to use UIpopoverController. I was using UIpopoverController in any earlier version, and I couldn't get it to work. Keep getting an error that the popoverController did not exist. Below is my code. Is there a framework that allows you to use UIPopoverController?
- (IBAction)getPhoto4:(id)sender {
if ([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeSavedPhotosAlbum])
{
UIImagePickerController *imagePicker =[[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.mediaTypes = #[(NSString *) kUTTypeImage ,(NSString *)kUTTypeMovie];
imagePicker.allowsEditing = NO;
[self presentViewController:imagePicker animated:YES completion:nil];
}
}
#pragma mark -
#pragma mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self dismissViewControllerAnimated:YES completion:nil];
UIImage *image = info[UIImagePickerControllerOriginalImage];
float actualHeight = image.size.height;
float actualWidth = image.size.width;
float imgRatio = actualWidth/actualHeight;
float maxRatio = 320.0/480.0;
if(imgRatio!=maxRatio){
if(imgRatio < maxRatio){
imgRatio = 480.0 / actualHeight;
actualWidth = imgRatio * actualWidth;
actualHeight = 480.0;
}
else{
imgRatio = 320.0 / actualWidth;
actualHeight = imgRatio * actualHeight;
actualWidth = 320.0;
}
}
CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
UIGraphicsBeginImageContext(rect.size);
[image drawInRect:rect];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Get the data for the image
NSData* imageData = UIImageJPEGRepresentation(img, 1.0);
// Give a name to the file
IMAGE_COUNTER = IMAGE_COUNTER + 1;
NSString* incrementedImgStr = [NSString stringWithFormat: #"zTempDataFilePleaseDelete%d.jpg", IMAGE_COUNTER];
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
// Now we get the full path to the file
NSString* fullPathToFile2 = [documentsDirectory stringByAppendingPathComponent:incrementedImgStr];
if(IMAGE_COUNTER == 4) {
imageView4.image = img;
photoHeight4 = img.size.height;
photoWidth4 = img.size.width;
photoPath4 = fullPathToFile2;
}
// and then we write it out
[imageData writeToFile:fullPathToFile2 atomically:NO];
}
-(void)image:(UIImage *)image
finishedSavingWithError:(NSError *)error
contextInfo:(void *)contextInfo
{
if (error) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"Save failed"
message: #"Failed to save image"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker1
{
[self dismissViewControllerAnimated:YES completion:nil];
}
On iPad you need to display UIImagePickerController embedded in UIPopoverController.
You can't directly display it using presentViewController:
If you are displaying camera then you can use presentViewController, else you need to use a popover for displaying the image picker in iPad.
Reference:
UIImagePickerController
So instead of:
[self presentViewController:imagePicker animated:YES completion:nil];
Use:
UIPopoverController *photoPop = [[UIPopoverController alloc]initWithContentViewController:imagePicker];
[photoPop presentPopoverFromRect:CGRectMake(100,100,300,300) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionDown animated:YES];
Check these tutorials:
UIImagePickerController
UIImagePickerController in iPad
try this code:
in .h file implement delegate
UIImagePickerControllerDelegate,UIPopoverControllerDelegate,UINavigationControllerDelegate
in .m file:
#implementation UIImagePickerController(Nonrotating)
- (BOOL)shouldAutorotate {
return NO;
}
#end
#implementation UINavigationController (Rotation_IOS6)
-(NSUInteger) supportedInterfaceOrientations {
return [self.topViewController supportedInterfaceOrientations];
}
-(BOOL)shouldAutorotate
{
return [[self.viewControllers lastObject] shouldAutorotate];
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return [[self.viewControllers lastObject] preferredInterfaceOrientationForPresentation];
}
#end
-(void)photoclick
{
UIImagePickerController *pckrImage=[[UIImagePickerController alloc]init];
pckrImage.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
pckrImage.allowsEditing = YES;
pckrImage.delegate=self;
// UITableViewCell *cell = [tblIncident cellForRowAtIndexPath:[tblIncident indexPathForSelectedRow]];
UIPopoverController * poppickePhoto = [[UIPopoverController alloc]initWithContentViewController:pckrImage];
poppickePhoto.delegate = self;
// poppickePhoto.popoverContentSize =CGSizeMake(320,480);
[poppickePhoto presentPopoverFromRect:yourbtn.frame inView:yourbtn.superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
update
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *choosedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
[picker dismissViewControllerAnimated:YES completion:NULL];
yourumageview.image=choosedImage;
[poppickePhoto dismissPopoverAnimated:YES];
}

Resources