ios 如何从照片库中选择图像并在应用程序中显示系统相机界面?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4812945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to select image from photo library and show the system camera interface within the app?
提问by Kuldeep Singh
How can I let a user select a photo from the Apple Photos library? How do we show the system camera UI to allow the user to take a picture?
如何让用户从 Apple 照片库中选择照片?我们如何显示系统相机 UI 以允许用户拍照?
回答by digitalHound
EDIT: March 15, 2016 - Here is a swift version of my prior answer, if you're looking for the objective-c version you'll find it below.
编辑:2016 年 3 月 15 日 - 这是我之前回答的快速版本,如果您正在寻找 Objective-c 版本,您会在下面找到它。
-- SWIFT --
-- 斯威夫特 --
First conform to the UIImagePickerControllerDelegate protocol and the UINavigationControllerDelegate protocol
首先符合 UIImagePickerControllerDelegate 协议和 UINavigationControllerDelegate 协议
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate
launch the image picker
启动图像选择器
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)
}
}
implement the delegate methods for UIImagePickerDelegate protocol
实现 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
}
-- OBJECTIVE-C --
-- 目标-C --
EDIT: Updated to check if camera is available before trying to launch it. Also added code showing how to save a png photo to the documents folder within the app sandbox.
编辑:更新以在尝试启动之前检查相机是否可用。还添加了显示如何将 png 照片保存到应用程序沙箱中的文档文件夹的代码。
Give this a try (this assumes using ARC).
试一试(这里假设使用 ARC)。
In the .h file conform to the delegate protocol:
在 .h 文件中符合委托协议:
@interface MyViewController : UIViewController <UINavigationControllerDelegate,UIImagePickerControllerDelegate>
In the .m file launch the image picker (camera):
在 .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;
}
}
Then implement the delegate protocols to handle a user cancel event or save/edit/etc the photo.
然后实现委托协议来处理用户取消事件或保存/编辑/等照片。
-(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];
}
ALSO ADDED IN EDIT: Here are the methods referenced it the Utilities class for getting the document path and current date/time
还添加了编辑:以下是引用它的方法 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;
}
回答by KingofBliss
You need to use UIImagePickerController.
您需要使用UIImagePickerController。
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
You have to implement the UIImagePickerControllerDelegate
method imagePickerController:didFinishPickingMediaWithInfo:
and then store the UIImage to wherever you want, with whatever file name you want, using NSFileManager methods.
您必须实现该UIImagePickerControllerDelegate
方法imagePickerController:didFinishPickingMediaWithInfo:
,然后使用 NSFileManager 方法将 UIImage 存储到您想要的任何位置,使用您想要的任何文件名。
回答by James Wolfe
Here's an updated version of digitalHound's answer which works for Swift 3.
这是适用于 Swift 3 的 digitalHound 答案的更新版本。
Action Launch Camera function:
动作发射相机功能:
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)
}
}
The Delegate Functions:
委托职能:
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
}
This is what worked for me.
这对我有用。
回答by Dasarsh Manikonda
Step 1 : Confirm to UIImagePickerControllerDelegate ,UINavigationControllerDelegate
第一步:确认 UIImagePickerControllerDelegate ,UINavigationControllerDelegate
Step 2: (iOS 10+) Add this as key to your info.plist file
Key : Privacy - Camera Usage Description
value: #Your message
第 2 步:(iOS 10+)将此作为键添加到您的 info.plist 文件 键:隐私 - 相机使用说明
值:#您的消息
Step 3: and this in your @IBAction
第 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)
}
回答by tryKuldeepTanwar
Quick Solution!
快速解决!
I created this libraryfor those you need to integrate this functionality immediately. You can also apply filters to your image with a single line of code all you have to write is :-
我为那些需要立即集成此功能的人创建了这个库。您还可以使用一行代码将过滤器应用于您的图像,您只需编写:-
let picker = PickerController()
picker.applyFilter = true // to apply filter after selecting the picture by default false
picker.selectImage(self){ image in
// Use the picture
}
回答by nik
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
this code will trigger device camera..
此代码将触发设备摄像头..
回答by IOS developer
//For Open 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];
}
// For Open Camera
// 对于打开的相机
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];
}
}