Expected ';' at end of declarations list error - ios

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

Related

Get PDF document height in iOS WebView

I am try to display a PDF in UIWebView via NSURL. It works fine.
But I do not know the height of pdf document. So sometimes it creates blank space or need to scroll. The PDF may also contain multiple pages.
I only want to show first page if it contain multi pages.
My code is as follow:
NSURL *url = [NSURL URLWithString:#"http://www.eecs.harvard.edu/econcs/pubs/online.pdf"];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
[web_large loadRequest:request];
[web_large setScalesPageToFit:YES];
Right now, the WebView has a fixed height
Pradumna Patil's answer is correct. I combined your code with his, and it worked fine. Just paste the following lines into your project and see for yourself:
UIWebView *web_large = [[UIWebView alloc]init];
[self.view addSubview:web_large];
NSURL *url = [NSURL URLWithString:#"https://www.truthinadvertising.org/wp-content/uploads/2014/09/App-Store-Review-Guidelines.pdf"];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
[web_large loadRequest:request];
[web_large setScalesPageToFit:YES];
CGPDFDocumentRef pdfDocumentRef = CGPDFDocumentCreateWithURL((CFURLRef)url);
CGPDFPageRef pdfPageRef = CGPDFDocumentGetPage(pdfDocumentRef, 1);
CGRect pdfPageRect = CGPDFPageGetBoxRect(pdfPageRef, kCGPDFMediaBox);
float width = pdfPageRect.size.width;
float height = pdfPageRect.size.height;
CGRect screenRect = [[UIScreen mainScreen]bounds];
web_large.frame = CGRectMake(0, 0, screenRect.size.width, height*screenRect.size.width/width);
Try this
There is this method:
size_t CGPDFDocumentGetNumberOfPages(CGPDFDocumentRef document)
That gives you the number of pages.
For ex.
NSURL *pdfUrl = [NSURL fileURLWithPath:yourPath];
CGPDFDocumentRef document = CGPDFDocumentCreateWithURL((CFURLRef)pdfUrl);
Below code gives height of single page in pdf file
float width = CGPDFPageGetBoxRect(pdfPageRef, kCGPDFMediaBox).size.width;
float height = CGPDFPageGetBoxRect(pdfPageRef, kCGPDFMediaBox).size.height;
Hope it helps.
in Swift you can do:
let documents = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
let writePath = documents?.appending("/myPdf.pdf")
let pdf: CGPDFDocument! = CGPDFDocument(URL.init(fileURLWithPath: writePath!) as CFURL)`enter code here`
let firstPage: CGPDFPage = pdf.page(at: 1)!
let heightFirstPage :CGRect = firstPage.getBoxRect(.mediaBox)
var heightPagePdf : CGFloat = heightFirstPage.height;
the variable 'pdf' also has a property 'numberOfPages', so you can know the entire height of pdf document (pdf.numberOfPages * heightPagePdf).
best regard
This one is easy.
You have to access the scrollview of the webView not the webview itself:
CGFloat totalHeight = self.webView.scrollView.contentSize.height;
Try this .. Its working fine
NSURL* pdfFileUrl = targetURL;
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfFileUrl);
CGFloat pdfHeight = 0;
NSUInteger totalNum = CGPDFDocumentGetNumberOfPages(pdf);
for(int i = 0; i < totalNum; i++ ) {
CGPDFPageRef myPageRef=CGPDFDocumentGetPage(pdf, i+1);
CGRect cropBox = CGPDFPageGetBoxRect(myPageRef, kCGPDFCropBox);
pdfHeight+=cropBox.size.height;
int pageRotation = CGPDFPageGetRotationAngle(myPageRef);
CGSize pageVisibleSize = CGSizeMake(cropBox.size.width, cropBox.size.height);
if ((pageRotation == 90) || (pageRotation == 270) ||(pageRotation == -90)) {
pageVisibleSize = CGSizeMake(cropBox.size.height, cropBox.size.width);
}
}
NSLog(#"%f",pdfHeight);
Instead of loading pdf in webView I would like to suggest you to draw PDF in UIView, Like I have done in my own project and it's working perfect.
Below is mine UIView subClass which draw pdf in UIView context.
PDFPage.h
#import <UIKit/UIKit.h>
#protocol PDFPageDelegate;
#interface PDFPage : UIView
#property uint currentPage;
#property unsigned long totalPages;
#property CGRect pageRect;
#property NSString *pdfPath;
#property id<PDFPageDelegate> delegate;
- (CGRect)setPdf:(NSString*)filePath;
- (void)swipeLeft;
- (void)swipeRight;
- (void)setPageNumber:(NSUInteger )targetPageNumber;
#end
#protocol PDFPageDelegate <NSObject>
- (void)pdfWillSwipeToLeft:(uint)upcommingPageNumber;
- (void)pdfWillSwipeToRight:(uint)upcommingPageNumber;
- (void)pdfTaped:(CGPoint)tapAt;
- (void)pdfDoubleTapped;
#end
PDFPage.m
#import "PDFPage.h"
#implementation PDFPage
#synthesize pageRect = _pageRect;
#synthesize currentPage = _currentPage;
#synthesize totalPages = _totalPages;
#synthesize delegate = _delegate;
#synthesize pdfPath = _pdfPath;
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {}
_currentPage = 1;
UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(swipeLeft)];
swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
[self addGestureRecognizer:swipeLeft];
UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(swipeRight)];
swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
[self addGestureRecognizer:swipeRight];
return self;
}
- (void)setPageNumber:(NSUInteger )targetPageNumber
{
_currentPage = (uint)targetPageNumber;
[self setNeedsDisplay];
[UIView transitionWithView:self duration:0.5
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
[self.layer displayIfNeeded];
} completion:nil];
}
- (void)swipeLeft
{
if(_currentPage == _totalPages)
return;
_currentPage++;
[_delegate pdfWillSwipeToLeft:_currentPage];
[self setNeedsDisplay];
[UIView transitionWithView:self duration:0.5
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
[self.layer displayIfNeeded];
} completion:nil];
}
- (void)swipeRight
{
if(_currentPage == 1)
return;
_currentPage--;
[_delegate pdfWillSwipeToRight:_currentPage];
[self setNeedsDisplay];
[UIView transitionWithView:self duration:0.5
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
[self.layer displayIfNeeded];
} completion:nil];
}
- (void)drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
// PDF might be transparent, assume white paper
[[UIColor whiteColor] set];
CGContextFillRect(ctx, rect);
// Flip coordinates
CGContextGetCTM(ctx);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -rect.size.height);
// url is a file URL
CFURLRef pdfURL = (__bridge CFURLRef)[NSURL fileURLWithPath:_pdfPath];
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL(pdfURL);
CGPDFPageRef page1 = CGPDFDocumentGetPage(pdf, _currentPage);
// get the rectangle of the cropped inside
CGRect mediaRect = CGPDFPageGetBoxRect(page1, kCGPDFCropBox);
CGContextScaleCTM(ctx, rect.size.width / mediaRect.size.width,
rect.size.height / mediaRect.size.height);
CGContextTranslateCTM(ctx, -mediaRect.origin.x, -mediaRect.origin.y);
// draw it
CGContextDrawPDFPage(ctx, page1);
CGPDFDocumentRelease(pdf);
}
- (CGRect)setPdf:(NSString*)filePath
{
_pdfPath =filePath;
_currentPage = 1;
CFURLRef pdfURL = (__bridge CFURLRef)[NSURL fileURLWithPath:_pdfPath];
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL(pdfURL);
CGPDFPageRef page = CGPDFDocumentGetPage(pdf,_currentPage);
_pageRect = CGPDFPageGetBoxRect(page, kCGPDFCropBox);
_totalPages = (CGPDFDocumentGetNumberOfPages(pdf));
[self setNeedsDisplay];
[UIView transitionWithView:self duration:0.5
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
[self setNeedsDisplay];
} completion:nil];
CGRect finalRect = CGRectMake(0, 0, _pageRect.size.width, _pageRect.size.height);
return finalRect;
}
How to use:-
NSData *pdfData = [NSData dataWithContentsOfURL:[NSURL URLWithString:pdfPath]]; // here pdfPath is webURL
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * savePDFAt = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
savePDFAt = [NSString stringWithFormat:#"%#/PDFs/",savePDFAt];
[[NSFileManager defaultManager] createDirectoryAtPath:savePDFAt withIntermediateDirectories:NO attributes:nil error:nil];
[savePDFAt stringByAppendingPathComponent:"test.pdf"];
if([pdfData writeToFile:savePDFAt options:0 error:&error])
NSLog(#"PDF download complete");
PDFPage *pdfPage = [PDFPage new];
pdfPage.alpha = 0.0f;
pdfPage.delegate = self;
pdfPage.frame = [pdfPage setPdf:pdfPath];
Then add this pdfPage to self's view or to scroller.

Saving Photo to a Specific Directory

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

saving photo automatically that is displayed in a UIIMage to a directory

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

Saving to directory does not work

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.

The difference between captureImage.image; and [captureImage].image;

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

Resources