打开相机在iphone应用程序 [英] opening camera in iphone app programatically

查看:156
本文介绍了打开相机在iphone应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在iphone应用程序中打开相机...喜欢使用imagepickerview我们可以打开图书馆...如何打开相机应用程序,以便我们可以拍照..

解决方案

编辑:2016年3月15日 - 这是一个快速版本的我的前一个答案,如果你正在寻找的目标c版本,你会发现它下面。 >

- SWIFT -



首先符合UIImagePickerControllerDelegate协议和UINavigationControllerDelegate协议

  class ViewController:UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate 

启动图片选择器

  func actionLaunchCamera()
{
如果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相机不可用,消息:无法在此设备上找到相机,preferredStyle:UIAlertControllerStyle.Alert)
self.presentViewController(alert,animated:true,completion:nil)
}
}

实现UIImagePickerDelegate协议的委托方法

  func imagePickerController(picker:UIImagePickerController,didFinishPickingMediaWithInfo info:[String:AnyObject])
{
//创建一个以当前日期/时间作为图像的文件路径name
let savePath:String = self.documentsPath()! +/+ self.presentDateTimeString()+.png

//如果有图像,尝试获取我们编辑的图像,以及原始图像
let editedImg:UIImage ? = info [UIImagePickerControllerEditedImage] as? UIImage
let originalImg:UIImage? = info [UIImagePickerControllerOriginalImage] as? UIImage

//如果我们有一个编辑的img创建我们的图像数据,否则使用原始图像
let imgData:NSData = editedImg == nil? UIImagePNGRepresentation(editedImg!)! :UIImagePNGRepresentation(originalImg!)!

//将图像数据写入文件
imgData.writeToFile(savePath,atomically:true)

//关闭选择器
self.dismissViewControllerAnimated (true,completion:nil)
}

func imagePickerControllerDidCancel(picker:UIImagePickerController)
{
//取消选择器取消选择器视图控制器
self .dismissViewControllerAnimated(true,completion:nil)
}


为方便/完整添加这些方法
func documentsPath() - > String?
{
//获取我们的路径
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.UserDomainMask,true)

如果paths.count> 0
{
//如果我们有一个返回我们的docs目录路径
let docsDir = paths [0]
return docsDir
}
return nil
}

func presentDateTimeString() - > String
{
//设置日期格式化程序
let dateFormatter:NSDateFormatter = NSDateFormatter dateFormatter.dateFormat =dd-MM-yyyy HH:mm:ss

//获取当前日期
现在:NSDate = NSDate()

/ /从现在起生成日期字符串
let theDateTime = dateFormatter.stringFromDate(now)
return theDateTime

}

- OBJECTIVE-C -



编辑:更新以检查相机是否可用,



尝试一下(假设使用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:@无法在设备上找到相机。
delegate:nil
cancelButtonTitle:@OK
otherButtonTitles:nil,nil];
[alert show];
alert = nil;
}
}

然后实现委托协议来处理用户取消事件

   - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *) info 
{
//这将创建一个文件路径,使用当前日期/时间作为保存图像的名称
NSString * presentTimeStamp = [Utilities getPresentDateTime];
NSString * fileSavePath = [Utilities documentsPath:presentTimeStamp];
fileSavePath = [fileSavePath stringByAppendingString:@。png];

//检查图像是否被编辑,如果它将编辑的版本保存为.png
if([info objectForKey:UIImagePickerControllerEditedImage]){
//保存编辑后的图像
NSData * imgPngData = UIImagePNGRepresentation([info objectForKey:UIImagePickerControllerEditedImage]);
[imgPngData writeToFile:fileSavePath atomically:YES];


} else {
//保存原始图像
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;
}


How to open camera in iphone app...Like using imagepickerview we can open the library..how to open the camera app so that we can take picture..

解决方案

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.

-- SWIFT --

First conform to the UIImagePickerControllerDelegate protocol and the UINavigationControllerDelegate protocol

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

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

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.

Give this a try (this assumes using ARC).

In the .h file conform to the delegate protocol:

@interface MyViewController : UIViewController <UINavigationControllerDelegate,UIImagePickerControllerDelegate>

In the .m file launch the image picker (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;
            }
}

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

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

这篇关于打开相机在iphone应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆