簡體   English   中英

如何從照片庫中選擇圖像並在應用程序中顯示系統相機界面?

[英]How to select image from photo library and show the system camera interface within the app?

如何讓用戶從Apple照片庫中選擇照片? 我們如何顯示系統相機用戶界面以允許用戶拍照?

編輯: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照片保存到應用程序沙箱中的documents文件夾中。

試試看(假設使用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];
}

還添加了編輯:這是Utilities類引用的方法,用於獲取文檔路徑和當前日期/時間

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

您需要使用UIImagePickerController

picker.sourceType = UIImagePickerControllerSourceTypeCamera;

您必須實現UIImagePickerControllerDelegate方法imagePickerController:didFinishPickingMediaWithInfo: ,然后使用NSFileManager方法將UIImage以所需的任何文件名存儲到所需的任何位置。

這是適用於Swift 3的digitalHound答案的更新版本。

動作啟動攝像頭功能:

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
    }

這對我有用。

步驟1:確認到UIImagePickerControllerDelegate,UINavigationControllerDelegate

步驟2:(iOS 10+)將此作為密鑰添加到您的info.plist文件中密鑰:隱私-相機使用說明
值:#您的留言

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

//對於開放畫廊

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];
    }
}
picker.sourceType = UIImagePickerControllerSourceTypeCamera;

此代碼將觸發設備攝像頭。

快速解決方案!

我為那些需要立即集成此功能的人創建了該 您還可以使用一行代碼將濾鏡應用於圖像,您只需編寫以下代碼:

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

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM