如何从照片库中选择图像并在应用程序中显示系统摄像头界面?

时间:2011-01-27 05:08:12

标签: ios camera uiimagepickercontroller

如何让用户从Apple照片库中选择照片?我们如何显示系统相机UI以允许用户拍照?

7 个答案:

答案 0 :(得分:8)

编辑:2016年3月15日 - 这是我之前答案的快速版本,如果您正在寻找您将在下面找到的objective-c版本。

- SWIFT -

首先符合UIImagePickerControllerDelegate协议和UINavigationControllerDelegate协议

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate

启动图像选择器

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)
    }
}

实现UIImagePickerDelegate协议的委托方法

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

}

- 目标-C -

编辑:更新以在尝试启动相机之前检查相机是否可用。还添加了代码,显示如何将png照片保存到应用程序沙箱中的文档文件夹。

尝试一下(假设使用ARC)。

在.h文件中符合委托协议:

@interface MyViewController : UIViewController <UINavigationControllerDelegate,UIImagePickerControllerDelegate>

在.m文件中启动图像选择器(相机):

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

然后实现委托协议来处理用户取消事件或保存/编辑/等照片。

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

还加入编辑: 以下是用于获取文档路径和当前日期/时间的实用程序类的方法

+(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;
}

答案 1 :(得分:5)

您需要使用UIImagePickerController

picker.sourceType = UIImagePickerControllerSourceTypeCamera;

您必须实现UIImagePickerControllerDelegate方法imagePickerController:didFinishPickingMediaWithInfo:,然后使用NSFileManager方法将UIImage存储到您想要的任何文件名。

答案 2 :(得分:1)

这是digitalHound的答案的更新版本,适用于Swift 3.

动作启动相机功能:

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)
    }

}

代表职能:

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
    }

这对我有用。

答案 3 :(得分:1)

步骤1:确认UIImagePickerControllerDelegate ,UINavigationControllerDelegate

步骤2:(iOS 10+)将此项添加为info.plist文件的密钥 密钥:隐私 - 相机使用说明
值:#Your message

第3步: 这在你的@IBAction

 if UIImagePickerController.isSourceTypeAvailable(.camera) {
        var imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .camera
        imagePicker.allowsEditing = false
        self.present(imagePicker, animated: true, completion: nil)
    }

答案 4 :(得分:0)

picker.sourceType = UIImagePickerControllerSourceTypeCamera;

此代码将触发设备相机..

答案 5 :(得分:0)

//适用于打开图库

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

//适用于打开相机

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

答案 6 :(得分:0)

快速解决方案!

我为需要立即集成此功能的用户创建了此library。您还可以使用一行代码将过滤器应用于图像,只需编写:-

let picker = PickerController()
picker.applyFilter = true // to apply filter after selecting the picture by default false
picker.selectImage(self){ image in
    // Use the picture
}

enter image description here