I am trying to use captureImage.image; in my code however can someone explain what this code will mean and which is correct captureImage.image; or [captureImage].image;
or [captureImage.image];
I am using it for this code
For .h
IBOutlet UIPickerView *SaveTopicker;
NSMutableArray *arraygenre;
}
#property(nonatomic, retain) AVCaptureStillImageOutput *stillImageOutput;
#property (weak, nonatomic) IBOutlet UILabel *categoryLabel;
#property (weak, nonatomic) IBOutlet UIView *imagePreview;
#property (weak, nonatomic) IBOutlet UIView *saveImage;
#property (weak, nonatomic) IBOutlet UIImageView *captureImage;
#property (weak, nonatomic) IBOutlet UISegmentedControl *cameraSwitch;
#property (weak, nonatomic) IBOutlet UIView *pickerViewContainer;
#property (nonatomic, retain) UIAccelerometer *accelerometer;
#property (weak,nonatomic) IBOutlet UIScrollView *BGScrollView;
- (IBAction)saveButton:(id)sender;
- (IBAction)closeButton:(id)sender;
- (IBAction)switchCamera:(id)sender;
- (IBAction)snapImage:(id)sender;
For implementation file
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//fetch Category Name from the array used to fill the Picker View
NSString *categoryName= [arraygenre objectAtIndex:row];
NSString *fPath = [documentsDirectory stringByAppendingPathComponent:categoryName];
NSFileManager *fileManager=[[NSFileManager alloc]init];
[fileManager createDirectoryAtPath:fPath withIntermediateDirectories:YES attributes:nil error:nil];
[captureImage.image];
[data writeToFile:fPath atomically:YES];
NSData *data= UIImagePNGRepresentation(image);
}
- (IBAction)snapImage:(id)sender {
if (!haveImage) {
captureImage.image = nil; //remove old image from view
captureImage.hidden = NO; //show the captured image view
imagePreview.hidden = YES; //hide the live video feed
[self capImage];
}
else {
captureImage.hidden = YES;
imagePreview.hidden = NO;
haveImage = NO;
}
}
- (void) capImage { //method to capture image from AVCaptureSession video feed
AVCaptureConnection *videoConnection = nil;
for (AVCaptureConnection *connection in stillImageOutput.connections) {
for (AVCaptureInputPort *port in [connection inputPorts]) {
if ([[port mediaType] isEqual:AVMediaTypeVideo] ) {
videoConnection = connection;
break;
}
}
if (videoConnection) {
break;
}
}
NSLog(#"about to request a capture from: %#", stillImageOutput);
[stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error) {
if (imageSampleBuffer != NULL) {
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
[self processImage:[UIImage imageWithData:imageData]];
}
}];
}
- (void) processImage:(UIImage *)image { //process captured image, crop, resize and rotate
haveImage = YES;
if([UIDevice currentDevice].userInterfaceIdiom==UIUserInterfaceIdiomPad) { //Device is ipad
// Resize image
UIGraphicsBeginImageContext(CGSizeMake(768, 1022));
[image drawInRect: CGRectMake(0, 0, 768, 1022)];
UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGRect cropRect = CGRectMake(0, 130, 768, 768);
CGImageRef imageRef = CGImageCreateWithImageInRect([smallImage CGImage], cropRect);
//or use the UIImage wherever you like
[captureImage setImage:[UIImage imageWithCGImage:imageRef]];
CGImageRelease(imageRef);
captureImage.hidden = NO;
}else{ //Device is iphone
// Resize image
UIGraphicsBeginImageContext(CGSizeMake(320, 426));
[image drawInRect: CGRectMake(0, 0, 320, 426)];
UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGRect cropRect = CGRectMake(0, 55, 320, 320);
CGImageRef imageRef = CGImageCreateWithImageInRect([smallImage CGImage], cropRect);
[captureImage setImage:[UIImage imageWithCGImage:imageRef]];
CGImageRelease(imageRef);
}
//adjust image orientation based on device orientation
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) {
NSLog(#"landscape left image");
[UIView beginAnimations:#"rotate" context:nil];
[UIView setAnimationDuration:0.5];
captureImage.transform = CGAffineTransformMakeRotation(DegreesToRadians(-90));
[UIView commitAnimations];
}
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight) {
NSLog(#"landscape right");
[UIView beginAnimations:#"rotate" context:nil];
[UIView setAnimationDuration:0.5];
captureImage.transform = CGAffineTransformMakeRotation(DegreesToRadians(90));
[UIView commitAnimations];
}
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortraitUpsideDown) {
NSLog(#"upside down");
[UIView beginAnimations:#"rotate" context:nil];
[UIView setAnimationDuration:0.5];
captureImage.transform = CGAffineTransformMakeRotation(DegreesToRadians(180));
[UIView commitAnimations];
}
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait) {
NSLog(#"upside upright");
[UIView beginAnimations:#"rotate" context:nil];
[UIView setAnimationDuration:0.5];
captureImage.transform = CGAffineTransformMakeRotation(DegreesToRadians(0));
[UIView commitAnimations];
}
}
However I am getting errors saying expected identifier on the first captureImage.image code
and use of undeclared identifier data on the[data writeToFile:fPath atomically:YES];and use of undeclared identifier image in the NSData *data= UIImagePNGRepresentation(image);
Did I do something wrong?
You could probably give some more information on what you're trying to achieve, and what isn't working. To answer your question: captureImage.image is the only one with valid syntax of the three
EDIT: I see you've updated you answer with some code, but it's not clear to me what the captureImage line should do.
captureImage.image calls the image method (usually a property) on the captureImage object, but there's no declaration for that object.
EDIT 2:
Assuming captureImage exists outside of this method, your last few lines should probably be something like this:
UIImage *image = captureImage.image;
NSData *data = UIImagePNGRepresentation(image);
[data writeToFile:fPath atomically:YES];
Related
I'm trying to resize an image in a photo app and haven't been successful yet. I'm new to photo resizing on iOS, but I swear that I'm doing this right, but my logs show:
Error: <WUTModelImageUploadReq>
[photo]: <nil>
[extension]: <nil>
</WUTModelImageUploadReq>
I'm trying to set 'scaleImage' as the image in the AsyncPostFeed.m
Here is my code:
UIImage+Scaling.m
#implementation UIImage (Scaling)
- (UIImage *)scaleImageToSize:(CGSize)newSize {
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
CGFloat originX = 0.0;
CGFloat originY = 0.0;
CGRect destinationRect =
CGRectMake(originX, originY, newSize.width, newSize.height);
[self drawInRect:destinationRect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
#end
WUTPostViewController.m:
- (void)viewDidLoad {
[super viewDidLoad];
UIImage *selectedImage = _imageForPost;
CGSize scaleSize = CGSizeMake(200.0f, 200.0f);
UIImage *scaleImage =
[selectedImage scaleImageToSize:scaleSize];
[self.imageViewForPost setImage:scaleImage];
...
}
WUTPostViewController.h:
#interface WUTPostViewController : WUTCommonViewController <UITextViewDelegate,UIAlertViewDelegate>
#property (strong, nonatomic) IBOutlet UILabel *lblUserName;
#property (strong, nonatomic) IBOutlet UIImageView *imageViewForPost;
#property (strong, nonatomic) IBOutlet UITextView *tvDesription;
#property (strong,nonatomic) UIImage *imageForPost;
#property (strong,nonatomic) UIImage *scaleImage;
- (void)wsPostLikeSuccessCallbackForPostId;
- (void)wsPostLikeFailCallbackWithMessage:(NSString *)errorMessage;
#end
AsyncPostFeed.m:
- (void)uploadPhoto {
WUTModelImageUploadReq *imageUploadReq = [[WUTModelImageUploadReq alloc]init];
// I'm trying to set scaleImage here
imageUploadReq.photo = [self encodeToBase64String:[UIImage imageWithData:UIImageJPEGRepresentation(self.viewControllerPost.scaleImage, 0.07f)]];
imageUploadReq.extension = #"jpg";
NSLog(#"Error: %#", imageUploadReq);
void (^wsSuccessHandler)(AFHTTPRequestOperation *operation, NSDictionary* responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject){
NSLog(#"Pull Feed responseObject %#",responseObject);
NSError *error;
WUTModelPostImageResponse *wsResponse = [[WUTModelPostImageResponse alloc]initWithDictionary:(NSDictionary *)responseObject error:&error];
if (error) {
errorMessage = #"Failure to upload image.";
NSLog(#"Error: %#", error);
[self postExecuteFail];
}else{
if (wsResponse.success) {
WUTModelImage *imageTemp = [wsResponse.data firstObject];
[postItem setObject:imageTemp.photo forKey:#"photo"];
[self uploadPostFeed];
}else{
errorMessage = #"Failure to upload image.";
NSLog(#"Error: %#", error);
[self postExecuteFail];
}
}
};
Update
Looks like you forgot to set local variable scaleImage to scaleImage property of WUTPostViewController class.
Try this code (last line should make the trick):
- (void)viewDidLoad {
[super viewDidLoad];
UIImage *selectedImage = _imageForPost;
CGSize scaleSize = CGSizeMake(200.0f, 200.0f);
UIImage *scaleImage =
[selectedImage scaleImageToSize:scaleSize];
[self.imageViewForPost setImage:scaleImage];
self.scaleImage = scaleImage;
...
}
Original Answer
Your resizing algorithm is correct. I use the same in my project and it perfectly works.
Looks like you send scaleImageToSize: message to nil object. That's why the result of this message is nil.
You can verify this assumption by updating code in this way:
- (void)viewDidLoad {
[super viewDidLoad];
UIImage *selectedImage = _imageForPost;
NSAssert(selectedImage != nil, #"Selected image is nil");
CGSize scaleSize = CGSizeMake(200.0f, 200.0f);
UIImage *scaleImage =
[selectedImage scaleImageToSize:scaleSize];
[self.imageViewForPost setImage:scaleImage];
...
}
As you see I added NSAssert call, so your application will crash with provided message if selected image is nil.
If NSAssert is triggered, then you need look for root cause of the problem. Basically you need verify that _imageForPost variable is initialized before viewDidLoad method is called.
Please check first image are not null
CGSize size1=CGSizeMake(300,300);
UIGraphicsBeginImageContext(size1);
[selectgalleryimage drawInRect:CGRectMake(0, 0,size1.width, size1.height)];
UIImage *SELECTED_IMG1 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
I declared the code
NSMutableArray *allImagesArray = [[NSMutableArray alloc]init];
however I get an error that is pointing at the = mark saying
Expected ';' at end of declarations list error and I do not think this is occurring with the spacing problem. What is happening?
- (void) processImage:(UIImage *)image { //process captured image, crop, resize and rotate
haveImage = YES;
if([UIDevice currentDevice].userInterfaceIdiom==UIUserInterfaceIdiomPad) { //Device is ipad
// Resize image
UIGraphicsBeginImageContext(CGSizeMake(768, 1022));
[image drawInRect: CGRectMake(0, 0, 768, 1022)];
UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGRect cropRect = CGRectMake(0, 130, 768, 768);
CGImageRef imageRef = CGImageCreateWithImageInRect([smallImage CGImage], cropRect);
//or use the UIImage wherever you like
[captureImage setImage:[UIImage imageWithCGImage:imageRef]];
CGImageRelease(imageRef);
}else{ //Device is iphone
// Resize image
UIGraphicsBeginImageContext(CGSizeMake(320, 426));
[image drawInRect: CGRectMake(0, 0, 320, 426)];
UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGRect cropRect = CGRectMake(0, 55, 320, 320);
CGImageRef imageRef = CGImageCreateWithImageInRect([smallImage CGImage], cropRect);
[captureImage setImage:[UIImage imageWithCGImage:imageRef]];
CGImageRelease(imageRef);
}
//adjust image orientation based on device orientation
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) {
NSLog(#"landscape left image");
[UIView beginAnimations:#"rotate" context:nil];
[UIView setAnimationDuration:0.5];
captureImage.transform = CGAffineTransformMakeRotation(DegreesToRadians(-90));
[UIView commitAnimations];
}
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight) {
NSLog(#"landscape right");
[UIView beginAnimations:#"rotate" context:nil];
[UIView setAnimationDuration:0.5];
captureImage.transform = CGAffineTransformMakeRotation(DegreesToRadians(90));
[UIView commitAnimations];
}
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortraitUpsideDown) {
NSLog(#"upside down");
[UIView beginAnimations:#"rotate" context:nil];
[UIView setAnimationDuration:0.5];
captureImage.transform = CGAffineTransformMakeRotation(DegreesToRadians(180));
[UIView commitAnimations];
}
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait) {
NSLog(#"upside upright");
[UIView beginAnimations:#"rotate" context:nil];
[UIView setAnimationDuration:0.5];
captureImage.transform = CGAffineTransformMakeRotation(DegreesToRadians(0));
[UIView commitAnimations];
NSArray *directoryNames = [NSArray arrayWithObjects:#"hats",#"bottoms",#"right",#"left",nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
for (int i = 0; i < [directoryNames count] ; i++) {
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:[directoryNames objectAtIndex:i]];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil]; //Create folder
NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:#"hats"]; // "right" is at index 2, per comments & code
NSString *filePath = [filePath stringByAppendingPathComponent:#"IMAGE_NAME_HERE.PNG"]; // you maybe want to incorporate a timestamp into the name to avoid duplicates
NSData *imageData = UIImagePNGRepresentation(captureImage.image);
[imageData writeToFile:filePath atomically:YES];
}
}
}
For sake of clarity in the discussion, what I mean is your header file (the .h file) should look like this:
// --------------------------------------------------------
// This is your class header file (it has a .h extension)
// --------------------------------------------------------
#import <UIKit/UIKit.h>
#interface MyClass : UIViewController
{
// ----------------------------------------------
// Declare your array here in the header file
// ----------------------------------------------
NSMutableArray *allImagesArray;
}
#end
And then in your implementation file (the .m file)
// --------------------------------------------------------
// This is your implementation file (it has a .m extension)
// --------------------------------------------------------
#implementation MyClass
-(id)init
{
self = [super init];
if(self)
{
// -----------------------------------------------
// Initialise your array here
// -----------------------------------------------
allImagesArray = [[NSMutableArray alloc] init];
}
return self;
}
// the rest of your code
#end
Update
Yes, you can also initialise your array in the viewDidLoad(). That's probably where you should do it :D
What I am saying is don't write this:
NSMutableArray *allImagesArray = [[NSMutableArray alloc ]allImagesArray = [[NSMutableArray alloc] init];
That is not valid syntax.
The syntax to declare and initialise is like this:
NSMutableArray *allImagesArray = [[NSMutableArray alloc] init];
But you cannot put that in the header file. So you should not do this:
// --------------------------------------------------------
// This is your class header file (it has a .h extension)
// --------------------------------------------------------
#import <UIKit/UIKit.h>
#interface MyClass : UIViewController
{
// ----------------------------------------------
// Don't write it like this
// ----------------------------------------------
NSMutableArray *allImagesArray = [[NSMutableArray alloc] init];
}
#end
I want to save photo in directory. However I made directories called hats bottoms right and left using this code in the view controller.
NSArray *directoryNames = [NSArray arrayWithObjects:#"hats",#"bottoms",#"right",#"left",nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
for (int i = 0; i < [directoryNames count] ; i++) {
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:[directoryNames objectAtIndex:i]];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil]; //Create folder
The UIImage is displaying what the user has shot in the camera in the app. I would want to save the photo automatically to one of my directories that I made(for example hats) when it is displayed on the UIIMage.Below is my code for displaying to UIImage after photo is taken. Is there away to automatically save to one of the directories?? I can't do the place where you save to a specific directory.
- (void) processImage:(UIImage *)image { //process captured image, crop, resize and rotate
haveImage = YES;
if([UIDevice currentDevice].userInterfaceIdiom==UIUserInterfaceIdiomPad) { //Device is ipad
// Resize image
UIGraphicsBeginImageContext(CGSizeMake(768, 1022));
[image drawInRect: CGRectMake(0, 0, 768, 1022)];
UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGRect cropRect = CGRectMake(0, 130, 768, 768);
CGImageRef imageRef = CGImageCreateWithImageInRect([smallImage CGImage], cropRect);
//or use the UIImage wherever you like
[captureImage setImage:[UIImage imageWithCGImage:imageRef]];
CGImageRelease(imageRef);
}else{ //Device is iphone
// Resize image
UIGraphicsBeginImageContext(CGSizeMake(320, 426));
[image drawInRect: CGRectMake(0, 0, 320, 426)];
UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGRect cropRect = CGRectMake(0, 55, 320, 320);
CGImageRef imageRef = CGImageCreateWithImageInRect([smallImage CGImage], cropRect);
[captureImage setImage:[UIImage imageWithCGImage:imageRef]];
CGImageRelease(imageRef);
}
//adjust image orientation based on device orientation
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) {
NSLog(#"landscape left image");
[UIView beginAnimations:#"rotate" context:nil];
[UIView setAnimationDuration:0.5];
captureImage.transform = CGAffineTransformMakeRotation(DegreesToRadians(-90));
[UIView commitAnimations];
}
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight) {
NSLog(#"landscape right");
[UIView beginAnimations:#"rotate" context:nil];
[UIView setAnimationDuration:0.5];
captureImage.transform = CGAffineTransformMakeRotation(DegreesToRadians(90));
[UIView commitAnimations];
}
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortraitUpsideDown) {
NSLog(#"upside down");
[UIView beginAnimations:#"rotate" context:nil];
[UIView setAnimationDuration:0.5];
captureImage.transform = CGAffineTransformMakeRotation(DegreesToRadians(180));
[UIView commitAnimations];
}
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait) {
NSLog(#"upside upright");
[UIView beginAnimations:#"rotate" context:nil];
[UIView setAnimationDuration:0.5];
captureImage.transform = CGAffineTransformMakeRotation(DegreesToRadians(0));
[UIView commitAnimations];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)switchCamera:(id)sender { //switch cameras front and rear cameras
if (cameraSwitch.selectedSegmentIndex == 0) {
FrontCamera = YES;
[self initializeCamera];
}
else {
FrontCamera = NO;
[self initializeCamera];
}
}
UPDATE
NSString *filePath = [folderPath stringByAppendingPathComponent:#"IMAGE_NAME_HERE.PNG"]; // you maybe want to incorporate a timestamp into the name to avoid duplicates
NSData *imageData = UIImagePNGRepresentation(captureImage.image);
[imageData writeToFile:filePath atomically:YES];
Automatically saving is just saving without explicitly asking the user if you should. The process of saving the image is identical:
Get your instance of UIImage
Convert to data (using UIImageJpegRepresentation or UIImagePngRepresentation)
Save the data (using writeToFile:atomically:)
Something like:
folderPath = [documentsDirectory stringByAppendingPathComponent:directoryNames[0]];
or
folderPath = [documentsDirectory stringByAppendingPathComponent:#"hats"];
I want to save photo in directory. However I made directories using this code in the view controller.
NSArray *directoryNames = [NSArray arrayWithObjects:#"hats",#"bottoms",#"right",#"left",nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
for (int i = 0; i < [directoryNames count] ; i++) {
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:[directoryNames objectAtIndex:i]];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil]; //Create folder
The UIImage is displaying what the user has taken. I would want to save the photo automatically to one of my directories that I made(for example hats) when it is displayed on the UIIMage.Below is my code for displaying to UIImage after photo is taken. Is there away to automatically save to one of the directories??
- (void) processImage:(UIImage *)image { //process captured image, crop, resize and rotate
haveImage = YES;
if([UIDevice currentDevice].userInterfaceIdiom==UIUserInterfaceIdiomPad) { //Device is ipad
// Resize image
UIGraphicsBeginImageContext(CGSizeMake(768, 1022));
[image drawInRect: CGRectMake(0, 0, 768, 1022)];
UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGRect cropRect = CGRectMake(0, 130, 768, 768);
CGImageRef imageRef = CGImageCreateWithImageInRect([smallImage CGImage], cropRect);
//or use the UIImage wherever you like
[captureImage setImage:[UIImage imageWithCGImage:imageRef]];
CGImageRelease(imageRef);
}else{ //Device is iphone
// Resize image
UIGraphicsBeginImageContext(CGSizeMake(320, 426));
[image drawInRect: CGRectMake(0, 0, 320, 426)];
UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGRect cropRect = CGRectMake(0, 55, 320, 320);
CGImageRef imageRef = CGImageCreateWithImageInRect([smallImage CGImage], cropRect);
[captureImage setImage:[UIImage imageWithCGImage:imageRef]];
CGImageRelease(imageRef);
}
//adjust image orientation based on device orientation
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) {
NSLog(#"landscape left image");
[UIView beginAnimations:#"rotate" context:nil];
[UIView setAnimationDuration:0.5];
captureImage.transform = CGAffineTransformMakeRotation(DegreesToRadians(-90));
[UIView commitAnimations];
}
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight) {
NSLog(#"landscape right");
[UIView beginAnimations:#"rotate" context:nil];
[UIView setAnimationDuration:0.5];
captureImage.transform = CGAffineTransformMakeRotation(DegreesToRadians(90));
[UIView commitAnimations];
}
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortraitUpsideDown) {
NSLog(#"upside down");
[UIView beginAnimations:#"rotate" context:nil];
[UIView setAnimationDuration:0.5];
captureImage.transform = CGAffineTransformMakeRotation(DegreesToRadians(180));
[UIView commitAnimations];
}
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait) {
NSLog(#"upside upright");
[UIView beginAnimations:#"rotate" context:nil];
[UIView setAnimationDuration:0.5];
captureImage.transform = CGAffineTransformMakeRotation(DegreesToRadians(0));
[UIView commitAnimations];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)switchCamera:(id)sender { //switch cameras front and rear cameras
if (cameraSwitch.selectedSegmentIndex == 0) {
FrontCamera = YES;
[self initializeCamera];
}
else {
FrontCamera = NO;
[self initializeCamera];
}
}
You probably want to put this at the bottom of processImage:
NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:directoryNames[2]]; // "right" is at index 2, per comments & code
NSString *filePath = [folderPath stringByAppendingPathComponent:#"IMAGE_NAME_HERE.PNG"]; // you maybe want to incorporate a timestamp into the name to avoid duplicates
NSData *imageData = UIImagePNGRepresentation(captureImage.image);
[imageData writeToFile:filePath atomically:YES];
I am trying to save a image to one of my directories that I made like this.
- (void) processImage:(UIImage *)image { //process captured image, crop, resize and rotate
haveImage = YES;
if([UIDevice currentDevice].userInterfaceIdiom==UIUserInterfaceIdiomPad) { //Device is ipad
// Resize image
UIGraphicsBeginImageContext(CGSizeMake(768, 1022));
[image drawInRect: CGRectMake(0, 0, 768, 1022)];
UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGRect cropRect = CGRectMake(0, 130, 768, 768);
CGImageRef imageRef = CGImageCreateWithImageInRect([smallImage CGImage], cropRect);
//or use the UIImage wherever you like
[captureImage setImage:[UIImage imageWithCGImage:imageRef]];
CGImageRelease(imageRef);
}else{ //Device is iphone
// Resize image
UIGraphicsBeginImageContext(CGSizeMake(320, 426));
[image drawInRect: CGRectMake(0, 0, 320, 426)];
UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGRect cropRect = CGRectMake(0, 55, 320, 320);
CGImageRef imageRef = CGImageCreateWithImageInRect([smallImage CGImage], cropRect);
[captureImage setImage:[UIImage imageWithCGImage:imageRef]];
CGImageRelease(imageRef);
}
//adjust image orientation based on device orientation
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) {
NSLog(#"landscape left image");
[UIView beginAnimations:#"rotate" context:nil];
[UIView setAnimationDuration:0.5];
captureImage.transform = CGAffineTransformMakeRotation(DegreesToRadians(-90));
[UIView commitAnimations];
}
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight) {
NSLog(#"landscape right");
[UIView beginAnimations:#"rotate" context:nil];
[UIView setAnimationDuration:0.5];
captureImage.transform = CGAffineTransformMakeRotation(DegreesToRadians(90));
[UIView commitAnimations];
}
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortraitUpsideDown) {
NSLog(#"upside down");
[UIView beginAnimations:#"rotate" context:nil];
[UIView setAnimationDuration:0.5];
captureImage.transform = CGAffineTransformMakeRotation(DegreesToRadians(180));
[UIView commitAnimations];
}
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait) {
NSLog(#"upside upright");
[UIView beginAnimations:#"rotate" context:nil];
[UIView setAnimationDuration:0.5];
captureImage.transform = CGAffineTransformMakeRotation(DegreesToRadians(0));
[UIView commitAnimations];
NSArray *directoryNames = [NSArray arrayWithObjects:#"hats",#"bottoms",#"right",#"left",nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
for (int i = 0; i < [directoryNames count] ; i++) {
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:[directoryNames objectAtIndex:i]];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil]; //Create folder
NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:#"hats"];
NSString *filePath = [filePath stringByAppendingPathComponent:#"IMAGE_NAME_HERE.PNG"];
NSData *imageData = UIImagePNGRepresentation(captureImage.image);
[imageData writeToFile:filePath atomically:YES];
However It does not work since I have made a collection view so that I can see what is saved. I would show the code for it if asks. Also I am getting warnings saying at the end of my code saying unused variable folder path and Variable file path is uninitialized when used within in its own initialization. My final goal is that user takes photo in directory hats. And it shows up in a collection view that is getting photo from directory hats. Is there any flaw in my code?
You're doing this:
NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:#"hats"];
NSString *filePath = [filePath stringByAppendingPathComponent:#"IMAGE_NAME_HERE.PNG"];
When I think you mean to be doing this:
NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:#"hats"];
NSString *filePath = [folderPath stringByAppendingPathComponent:#"IMAGE_NAME_HERE.PNG"];
Basically, you have an unused variable warning for folderPath because you mistakenly wrote NSString *filePath = [filePath ... which ignores folder path altogether, creates a blank string, and then appends your file name to it. If you logged this string you would see that it outputs only your file name, without the path to the documents directory prepended to it.