iOS相机操作笔记

最近忙于项目,需要拍摄图片,这里先列出部分测试代码。

//
//  FirstViewController.m
//  UiTest
//
//  Created by Tang Huaming on 16/8/13.
//  Copyright © 2016年 唐华明. All rights reserved.
//

#import "FirstViewController.h"
#import "SecondViewController.h"

// 相机应用需要遵守2个协议
@interface FirstViewController () <UIActionSheetDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate>
- (IBAction)goToSecondVC:(id)sender;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@property (strong, nonatomic) UIImagePickerController *picker;
@property (strong, nonatomic) UIActionSheet *actionSheet;

@end

@implementation FirstViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    _picker = [[UIImagePickerController alloc] init];
    _picker.delegate = self;
    _picker.allowsEditing = YES; //如果需要对图片进行修改
    
    // UIImagePickerControllerSourceTypeSavedPhotosAlbum //来自相册
    // UIImagePickerControllerSourceTypePhotoLibrary     //来自图库
    // UIImagePickerControllerSourceTypeCamera           //来自相机
    
    // 设置源类型之前,需要检查相机是否可用
//    if (![self isCameraAvailable]){
//        _picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
//    }else{
//        _picker.sourceType = UIImagePickerControllerSourceTypeCamera;
//        _picker.showsCameraControls = YES; //显示拍照下方的工具栏
//    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/* 字典info中的键
 NSString *const  UIImagePickerControllerMediaType;指定用户选择的媒体类型
 NSString *const  UIImagePickerControllerOriginalImage ;原始图片
 NSString *const  UIImagePickerControllerEditedImage ;修改后的图片
 NSString *const  UIImagePickerControllerCropRect ;裁剪尺寸
 NSString *const  UIImagePickerControllerMediaURL ;媒体的URL
 NSString *const  UIImagePickerControllerReferenceURL ;原件的URL
 NSString *const  UIImagePickerControllerMediaMetadata;当来数据来源是照相机的时候这个值才有效
}
*/
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSLog(@"完成照片选择返回------------------>");
    
    UIImage *image = nil;
    if ([picker allowsEditing]){
        // 获取照片的原图
        image = [info objectForKey:UIImagePickerControllerEditedImage];
    }else{
        // 获得编辑后的图片
        image = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    
    // 显示图片
    [_imageView setImage:image];
    
    // 保存图片到相册
    SEL selectorToCall = @selector(image:didFinishSavingWithError:contextInfo:);
    UIImageWriteToSavedPhotosAlbum(image, self, selectorToCall, nil);
    
    // Create paths to output images
    NSString  *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.png"];
    NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.jpg"];
    
    NSLog(@"Path: %@", jpgPath);
    
    // Write a UIImage to JPEG with minimum compression (best quality)
    // The value 'image' must be a UIImage object
    // The value '1.0' represents image compression quality as value from 0.0 to 1.0
    // 可以设置压缩率,数值越小,保存的图片占用空间越小
    [UIImageJPEGRepresentation(image, 0.3) writeToFile:jpgPath atomically:YES];
    
    // Write image to PNG
    [UIImagePNGRepresentation(image) writeToFile:pngPath atomically:YES];
    
    // Let's check to see if files were successfully written...
    
    // Create file manager
    NSError *error;
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    
    // Point to Document directory
    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    
    // Write out the contents of home directory to console
    // 返回文件名称的数组
    NSLog(@"Documents directory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
    
    // 关闭
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    NSLog(@"取消照片选择返回");
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

// 保存图片失败时调用
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo: (void *)contextInfo
{
    if (error != nil)
    {
        NSLog(@"Image Can not be saved");
    }
    else
    {
        NSLog(@"Successfully saved Image");
    }
}

// 相机是否可用
- (BOOL)isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

// 图库是否可用
- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary];
}

// 相册是否可用
- (BOOL) isPhotoAlbumAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
}

// 前面的摄像头是否可用
- (BOOL)isFrontCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

// 后面的摄像头是否可用
- (BOOL)isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

// 判断是否支持某种多媒体类型:拍照,视频
- (BOOL)cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0){
        NSLog(@"Media type is empty.");
        return NO;
    }
    NSArray *availableMediaTypes =[UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL*stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}



- (void)callActionSheetFunc{
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        self.actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择图像"
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                         destructiveButtonTitle:nil
                                              otherButtonTitles:@"拍照", @"从相册选择", nil,nil];
    }else{
        self.actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择图像"
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                         destructiveButtonTitle:nil
                                              otherButtonTitles:@"从相册选择", nil, nil];
    }
    
    self.actionSheet.tag = 1000;
    [self.actionSheet showInView:self.view];
}

// Called when a button is clicked. The view will be automatically dismissed after this call returns
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag == 1000) {
        NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            switch (buttonIndex) {
                case 0:
                    //来源:相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 1:
                    //来源:相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                case 2:
                    return;
            }
        }
        else {
            if (buttonIndex == 2) {
                return;
            } else {
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
        // 跳转到相机或相册页面
        _picker.sourceType = sourceType;
        
        [self presentViewController:_picker animated:YES completion:^{
            
        }];
    }
}

- (IBAction)goToSecondVC:(id)sender {
    [self callActionSheetFunc];
}

@end

 

posted @ 2016-09-06 22:49  XiaoManon  阅读(343)  评论(0编辑  收藏  举报