2013-08-15 3 views
0

Я хочу сохранить фотографию в каталоге. Однако я сделал каталоги под названием «шляпы» внизу справа и слева, используя этот код в контроллере представления.Сохранение фотографии в конкретном каталоге

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 

UIImage показывает, что пользователь снял в камере в приложении. Я хотел бы сохранить фотографию автоматически в один из моих каталогов, который я сделал (например, шляпы), когда он отображается в UIIMage.Below - это мой код для отображения UIImage после того, как сделана фотография. Есть ли возможность автоматического сохранения в один из каталогов? Я не могу сделать то место, где вы сохраняете конкретный каталог.

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

ответ

0

Автоматическое сохранение только сохранения без явного запроса пользователю, если вы должны. Процесс сохранения изображения идентичен:

  1. Получите ваш экземпляр UIImage
  2. Преобразовать в данных (с использованием UIImageJpegRepresentation или UIImagePngRepresentation)
  3. сохранить данные (используя writeToFile:atomically:)

Нечто вроде:

folderPath = [documentsDirectory stringByAppendingPathComponent:directoryNames[0]]; 

или

folderPath = [documentsDirectory stringByAppendingPathComponent:@"hats"]; 
+0

Ok Я Я сделал то, что вы сказали мне, однако я до сих пор не понимаю, как указать директорию, что я сделал. Я просто хочу сохранить изображение в директории справа. – Shouri

+0

В коде в верхней части вашего вопроса вы получаете пути к каталогам, чтобы обеспечить их существование ... – Wain

+0

'NSString * folderPath = [NSDocumentDirectory stringByAppendingPathComponent: directoryNames [%]];' Вы имеете в виду это? Я где вы помещаете имя каталога? – Shouri

Смежные вопросы