我正在尝试让我的应用程序打开相机应用程序以拍摄保存图片。
从我的应用程序中我启动相机应用程序以使用以下代码拍照:
-(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];
}
我的问题是按下按钮后,相机会出来让我拍照。拍摄照片后,会显示图像,我可以选择“重拍”或“使用”。我的问题是,如果我点击“使用”,图像不会保存到相机胶卷。是否有可能保存图像并最终更改“使用”按钮以说“保存”?
谢谢你的帮助!
答案 0 :(得分:3)
照片未保存,因为您从未真正添加代码以将图像保存到didFinishPickingMediaWithInfo:
委托方法。您所要做的就是将您在TakePhoto:
中注释掉的行添加到此功能中,然后您就可以将照片保存到相机胶卷中。 E.x:
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
image = [info objectForKey:UIImagePickerControllerOriginalImage];
UIImageWriteToSavedPhotosAlbum(image, nil, nil, NULL);
[self dismissViewControllerAnimated:YES completion:NULL];
}
答案 1 :(得分: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]