通過調用系統攝像頭拍照,拍視訊,然後寫入檔案的
時間: 2010-06-08 16:50 點選: 294 次
如果您的App裡需要獲得由系統自帶的照相機、錄影機和錄音軟體所生成的檔案。可以借鑒以下代碼來調用iPhone攝像頭拍照或者攝像的功能,并把獲得的資料直接寫入到檔案。 //這一段是 如果您的App裡需要獲得由系統自帶的照相機、錄影機和錄音軟體所生成的檔案。可以借鑒以下代碼來調用iPhone攝像頭拍照或者攝像的功能,并把獲得的資料直接寫入到檔案。
//這一段是,點選一個takePicture按鈕的操作.
- (IBAction)takePicture:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
NSArray *temp_MediaTypes = [UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
picker.mediaTypes = temp_MediaTypes;
picker.delegate = self;
picker.allowsImageEditing = YES;
}
[self presentModalViewController:picker animated:YES];
[picker release];
}
//下面兩個函數是遵守 UIImagePickerControllerDelegate這個協定所實作的類.這樣就能夠完整的實作,擷取照片或者視訊,然後寫入檔案的過程.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if ([mediaType isEqualToString:@"public.image"]){
UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
NSLog(@"found an image");
NSString *imageFile = [documentsDirectory stringByAppendingPathComponent:@"temp.jpg"];
NSLog(@"%@", imageFile);
success = [fileManager fileExistsAtPath:imageFile];
if(success) {
success = [fileManager removeItemAtPath:imageFile error:&error];
}
imageView.image = image;
[UIImageJPEGRepresentation(image, 1.0f) writeToFile:imageFile atomically:YES];
//SETIMAGE(image);
//CFShow([[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingString:@"/Documents"]]);
}
else if([mediaType isEqualToString:@"public.movie"]){
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(@"%@", videoURL);
NSLog(@"found a video");
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSString *videoFile = [documentsDirectory stringByAppendingPathComponent:@"temp.mov"];
NSLog(@"%@", videoFile);
success = [fileManager fileExistsAtPath:videoFile];
if(success) {
success = [fileManager removeItemAtPath:videoFile error:&error];
}
[videoData writeToFile:videoFile atomically:YES];
//CFShow([[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingString:@"/Documents"]]);
//NSLog(videoURL);
}
[picker dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissModalViewControllerAnimated:YES];
}
歡迎進入CocoaChina論壇參與讨論,本帖位址 http://www.cocoachina.com/bbs/read.php?tid-18588.html