2

我正在尝试让我的应用程序打开相机应用程序以保存照片。

从我的应用程序中,我正在启动相机应用程序以使用以下代码拍照:

-(IBAction)TakePhoto:(id)sender {

    picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    [picker setSourceType:UIImagePickerControllerSourceTypeCamera];
    [self presentViewController:picker animated:YES completion:NULL];
    [picker release];
    //save image??:
    //UIImageWriteToSavedPhotosAlbum(UIImage *image, id completionTarget, SEL completionSelector, void *contextInfo);
}

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    image = [info objectForKey:UIImagePickerControllerOriginalImage];

    [self dismissViewControllerAnimated:YES completion:NULL];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {

    [self dismissViewControllerAnimated:YES completion:NULL];
}

我的问题是,一旦按下按钮,相机就会出来并让我拍照。拍完照片后,图像就会显示出来,我可以选择“重拍”或“使用”。我的问题是,如果我单击“使用”,图像不会保存到相机胶卷中。是否有可能保存图像并最终将“使用”按钮更改为“保存”?

谢谢你的帮助!

4

2 回答 2

3

未保存照片,因为您从未实际添加代码以将图像保存到didFinishPickingMediaWithInfo:委托方法。您所要做的就是将您注释掉的行添加TakePhoto:到此功能中,您就可以将照片保存到相机胶卷中。前任:

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    image = [info objectForKey:UIImagePickerControllerOriginalImage];

    UIImageWriteToSavedPhotosAlbum(image, nil, nil, NULL);

    [self dismissViewControllerAnimated:YES completion:NULL];
}
于 2013-10-16T17:10:19.840 回答
1
static NSDateFormatter* dateFormatter;    
- (NSString*) generateNameWithExtension: (NSString*) extension
{
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"yyyyMMddHHmmssSSS";
    });

    NSDate* now = [NSDate date];
    NSString* string = [dateFormatter stringFromDate:now];
    string = [NSString stringWithFormat:@"%@.%@",string,extension];
    return string;
}


- (NSString*) saveImage: (UIImage*) image WithExtension: (NSString*) extension
{
    extension = [extension lowercaseString];
    NSData* data;

    if ([extension isEqualToString:@"png"])
    {
        data = UIImagePNGRepresentation(image);
    }else if ([extension isEqualToString:@"jpg"]||[extension isEqualToString:@"jpeg"])
    {
        data = UIImageJPEGRepresentation(image, 1.0);
    }else{
        NSLog(@"Error save local image, Extension: (%@) is not recognized, use (PNG/JPG)",extension);
        return nil;
    }
    NSString* imageName = [self generateNameWithExtension:extension];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documents = [paths objectAtIndex:0];
    NSString *finalPath = [documents stringByAppendingPathComponent:imageName];

    [data writeToFile:finalPath options:NSAtomicWrite error:nil];
    return finalPath;
}

此代码将图像保存在您的应用程序文件夹中。您可以稍后使用它:[UIImage imageWithContentsOfFile:finalPath]

于 2013-10-16T17:27:19.903 回答