2011-01-27 41 views

Trả lời

5

Bạn cần phải sử dụng UIImagePickerController.

picker.sourceType = UIImagePickerControllerSourceTypeCamera; 

Bạn cần phải thực hiện các phương pháp UIImagePickerControllerDelegateimagePickerController:didFinishPickingMediaWithInfo: và sau đó lưu trữ các UIImage đến bất cứ nơi nào bạn muốn, với bất cứ tên tập tin mà bạn muốn, sử dụng phương pháp NSFileManager.

+0

thế nào để mở camera ở chỗ ... bạn có thể gửi một số mẫu code ... –

+0

đọc tài liệu, nó chứa mã mẫu – KingofBliss

+0

một câu hỏi nữa .. làm cách nào chúng tôi có thể tải hình ảnh/audio/video lên máy chủ trong iphone ..? bạn có thể đưa ra bất kỳ liên kết hữu ích nào không ....? –

0
picker.sourceType = UIImagePickerControllerSourceTypeCamera; 

mã này sẽ kích hoạt camera của điện thoại ..

+0

- (IBAction) grabImage: (id) người gửi { \t UIImagePickerController * picker = [[UIImagePickerController alloc] init]; \t picker.delegate = self; \t picker.allowsEditing = YES; \t picker.sourceType = UIImagePickerControllerSourceTypeCamera; \t [self presentModalViewController: bộ chọn hoạt ảnh: YES]; \t [bản phát hành bộ chọn]; } – nik

+0

một câu hỏi khác .. làm cách nào chúng tôi có thể tải hình ảnh/âm thanh/video lên máy chủ trong iphone ..? Bạn có thể cung cấp bất kỳ liên kết hữu ích nào không ....? –

+0

@kuldeep chuyển đổi chúng thành NSData và sau đó tải lên máy chủ – KingofBliss

8

EDIT: 15 tháng 3 năm 2016 - Dưới đây là một phiên bản nhanh chóng của câu trả lời trước của tôi, nếu bạn đang tìm kiếm các phiên bản Objective-C bạn sẽ tìm thấy nó dưới đây.

- SWIFT -

Đầu tiên phù hợp với các giao thức UIImagePickerControllerDelegate và giao thức UINavigationControllerDelegate

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate 

ra mắt bảng chọn hình ảnh

func actionLaunchCamera() 
{ 
    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) 
    { 
     let imagePicker:UIImagePickerController = UIImagePickerController() 
     imagePicker.delegate = self 
     imagePicker.sourceType = UIImagePickerControllerSourceType.Camera 
     imagePicker.allowsEditing = true 

     self.presentViewController(imagePicker, animated: true, completion: nil) 
    } 
    else 
    { 
     let alert:UIAlertController = UIAlertController(title: "Camera Unavailable", message: "Unable to find a camera on this device", preferredStyle: UIAlertControllerStyle.Alert) 
     self.presentViewController(alert, animated: true, completion: nil) 
    } 
} 

thực hiện các phương pháp đại biểu cho UIImagePickerDelegate giao thức

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) 
{ 
    // create a filepath with the current date/time as the image name 
    let savePath:String = self.documentsPath()! + "/" + self.presentDateTimeString() + ".png" 

    // try to get our edited image if there is one, as well as the original image 
    let editedImg:UIImage? = info[UIImagePickerControllerEditedImage] as? UIImage 
    let originalImg:UIImage? = info[UIImagePickerControllerOriginalImage] as? UIImage 

    // create our image data with the edited img if we have one, else use the original image 
    let imgData:NSData = editedImg == nil ? UIImagePNGRepresentation(editedImg!)! : UIImagePNGRepresentation(originalImg!)! 

    // write the image data to file 
    imgData.writeToFile(savePath, atomically: true) 

    // dismiss the picker 
    self.dismissViewControllerAnimated(true, completion: nil) 
} 

func imagePickerControllerDidCancel(picker: UIImagePickerController) 
{ 
    // picker cancelled, dismiss picker view controller 
    self.dismissViewControllerAnimated(true, completion: nil) 
} 


// added these methods simply for convenience/completeness 
func documentsPath() ->String? 
{ 
    // fetch our paths 
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) 

    if paths.count > 0 
    { 
     // return our docs directory path if we have one 
     let docsDir = paths[0] 
     return docsDir 
    } 
    return nil 
} 

func presentDateTimeString() ->String 
{ 
    // setup date formatter 
    let dateFormatter:NSDateFormatter = NSDateFormatter() 
    dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss" 

    // get current date 
    let now:NSDate = NSDate() 

    // generate date string from now 
    let theDateTime = dateFormatter.stringFromDate(now) 
    return theDateTime 

} 

- MỤC TIÊU-C -

CHỈNH SỬA: Cập nhật để kiểm tra xem máy ảnh có khả dụng hay không trước khi khởi chạy. Cũng thêm mã cho biết cách lưu ảnh png vào thư mục tài liệu trong hộp cát ứng dụng.

Dùng thử (điều này giả định sử dụng ARC).

Trong file .h phù hợp với các giao thức đại biểu:

@interface MyViewController : UIViewController <UINavigationControllerDelegate,UIImagePickerControllerDelegate> 

Trong tập tin .m khởi động hộp thoại chọn hình ảnh (camera):

-(void)actionLaunchAppCamera 
{ 
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) 
      { 
       UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init]; 
       imagePicker.delegate = self; 
       imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; 
       imagePicker.allowsEditing = YES; 

       [self presentModalViewController:imagePicker animated:YES]; 
      }else{ 
       UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Camera Unavailable" 
                   message:@"Unable to find a camera on your device." 
                   delegate:nil 
                cancelButtonTitle:@"OK" 
                otherButtonTitles:nil, nil]; 
       [alert show]; 
       alert = nil; 
      } 
} 

Sau đó, thực hiện các giao thức đại biểu để xử lý một người dùng hủy bỏ sự kiện hoặc lưu/chỉnh sửa/etc ảnh.

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 
{ 
    //This creates a filepath with the current date/time as the name to save the image 
    NSString *presentTimeStamp = [Utilities getPresentDateTime]; 
    NSString *fileSavePath = [Utilities documentsPath:presentTimeStamp]; 
    fileSavePath = [fileSavePath stringByAppendingString:@".png"]; 

//This checks to see if the image was edited, if it was it saves the edited version as a .png 
if ([info objectForKey:UIImagePickerControllerEditedImage]) { 
    //save the edited image 
    NSData *imgPngData = UIImagePNGRepresentation([info objectForKey:UIImagePickerControllerEditedImage]); 
    [imgPngData writeToFile:fileSavePath atomically:YES]; 


}else{ 
    //save the original image 
    NSData *imgPngData = UIImagePNGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage]); 
    [imgPngData writeToFile:fileSavePath atomically:YES]; 

} 

[self dismissModalViewControllerAnimated:YES]; 

} 

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker 
{ 
    [self dismissModalViewControllerAnimated:YES]; 
} 

CŨNG thêm vào EDIT: Sau đây là các phương pháp tham chiếu nó lớp Utilities để nhận được đường dẫn tài liệu và ngày hiện tại/lần

+(NSString *)documentsPath:(NSString *)fileName { 
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    return [documentsDirectory stringByAppendingPathComponent:fileName]; 
} 


+(NSString *)getPresentDateTime{ 

    NSDateFormatter *dateTimeFormat = [[NSDateFormatter alloc] init]; 
    [dateTimeFormat setDateFormat:@"dd-MM-yyyy HH:mm:ss"]; 

    NSDate *now = [[NSDate alloc] init]; 

    NSString *theDateTime = [dateTimeFormat stringFromDate:now]; 

    dateTimeFormat = nil; 
    now = nil; 

    return theDateTime; 
} 
0

// Đối mở Gallery

UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init]; 
imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; 
imagePickerController.delegate = self; 
if([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) 
{ 
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{ 

     [self presentViewController:imagePickerController animated:YES completion:nil]; 
    }]; 
} 
else{ 

    [self presentViewController:imagePickerController animated:YES completion:nil]; 
} 

// Để mở Máy ảnh

if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) 
{ 
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init]; 
    imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen; 
    imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera; 
    imagePickerController.delegate = self; 
    if([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) 
    { 
     [[NSOperationQueue mainQueue] addOperationWithBlock:^{ 

      [self presentViewController:imagePickerController animated:YES completion:nil]; 
     }]; 
    } 
    else{ 
     [self presentViewController:imagePickerController animated:YES completion:nil]; 
    } 
} 
0

Đây là phiên bản cập nhật của câu trả lời của DigitalHound hoạt động cho Swift 3.

Hành động chức năng Launch Camera:

func actionLaunchCamera() 
{ 
    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) 
    { 
     let imagePicker:UIImagePickerController = UIImagePickerController() 
     imagePicker.delegate = self 
     imagePicker.sourceType = UIImagePickerControllerSourceType.camera 
     imagePicker.allowsEditing = true 

     self.present(imagePicker, animated: true, completion: nil) 
    } 
    else 
    { 
     let alert:UIAlertController = UIAlertController(title: "Camera Unavailable", message: "Unable to find a camera on this device", preferredStyle: UIAlertControllerStyle.alert) 
     alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil)) 
     alert.view.tintColor = UIColor(red:0.37, green:0.66, blue:0.44, alpha:1.0) 
     self.present(alert, animated: true, completion: nil) 
    } 

} 

Các chức năng đại biểu:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { 
     // create a filepath with the current date/time as the image name 
     let savePath:URL = URL(fileURLWithPath: self.documentsPath()! + "/" + self.presentDateTimeString() + ".png") 
     // try to get our edited image if there is one, as well as the original image 
     let editedImg:UIImage? = info[UIImagePickerControllerEditedImage] as? UIImage 
     let originalImg:UIImage? = info[UIImagePickerControllerOriginalImage] as? UIImage 

     // create our image data with the edited img if we have one, else use the original image 
     let imgData:Data = editedImg == nil ? UIImagePNGRepresentation(editedImg!)! : UIImagePNGRepresentation(originalImg!)! as Data 

     // write the image data to file 
     try! imgData.write(to: savePath, options: []) 

     // dismiss the picker 
     self.dismiss(animated: true, completion: nil) 
    } 

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { 
     // picker cancelled, dismiss picker view controller 
     self.dismiss(animated: true, completion: nil) 
    } 


    // added these methods simply for convenience/completeness 
    func documentsPath() ->String? 
    { 
     // fetch our paths 
     let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true) 

     if paths.count > 0 
     { 
      // return our docs directory path if we have one 
      let docsDir = paths[0] 
      return docsDir 
     } 
     return nil 
    } 

    func presentDateTimeString() ->String 
    { 
     // setup date formatter 
     let dateFormatter:DateFormatter = DateFormatter() 
     dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss" 

     // get current date 
     let now:Date = Date() 

     // generate date string from now 
     let theDateTime = dateFormatter.string(from: now) 
     return theDateTime 
    } 

Đây là những gì làm việc cho tôi.

0

Bước 1: Xác nhận để UIImagePickerControllerDelegate , UINavigationControllerDelegate

Bước 2: (iOS 10+) Thêm này như chìa khóa để tập tin info.plist của bạn chính: Bảo mật - Máy ảnh Cách sử dụng Mô tả
giá trị: Thông điệp #Your

Bước 3: và điều này trong @IBAction bạn

if UIImagePickerController.isSourceTypeAvailable(.camera) { 
     var imagePicker = UIImagePickerController() 
     imagePicker.delegate = self 
     imagePicker.sourceType = .camera 
     imagePicker.allowsEditing = false 
     self.present(imagePicker, animated: true, completion: nil) 
    } 
Các vấn đề liên quan