系統自帶UIImagePickerController的用法
調用方式
UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
//sourceType = UIImagePickerControllerSourceTypeCamera; //照相機
//sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //圖檔庫
//sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum; //儲存的相片
if(self.picker == nil){
self.picker = [[UIImagePickerController alloc] init];//初始化
self.picker.delegate = self;
self.picker.allowsEditing = NO;//設定可編輯
self.picker.sourceType = sourceType;
}
[self presentViewController:self.picker animated:true completion:nil];
複制
回調
//當選擇一張圖檔後進入這裡
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
//當選擇的類型是圖檔
if ([type isEqualToString:@"public.image"]){
//先把圖檔轉成NSData
UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
image = [self fixOrientation:image];
NSData *data;
data = UIImageJPEGRepresentation(image, 0.5);
NSString * md5Str = [data MD5HexDigest];
//圖檔儲存的路徑
//這裡将圖檔放在沙盒的documents檔案夾中
NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString * fileName = [NSString stringWithFormat:@"%@.jpg",md5Str];
//得到選擇後沙盒中圖檔的完整路徑
_filePath = [[NSString alloc]initWithFormat:@"%@/%@",DocumentsPath,fileName];
//檔案管理器
NSFileManager *fileManager = [NSFileManager defaultManager];
//把剛剛圖檔轉換的data對象拷貝至沙盒中 并儲存為image.jpg
[fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
[fileManager createFileAtPath:_filePath contents:data attributes:nil];
NSLog(@"檔案的路徑為:%@",_filePath);
}
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
NSLog(@"您取消了選擇圖檔");
[self.picker dismissViewControllerAnimated:true completion:^{
}];
}
複制
拍照後的圖檔90度旋轉的解決方法
-(UIImage *)fixOrientation:(UIImage *)aImage {
// No-op if the orientation is already correct
if (aImage.imageOrientation == UIImageOrientationUp)
return aImage;
// We need to calculate the proper transformation to make the image upright.
// We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
CGAffineTransform transform = CGAffineTransformIdentity;
switch (aImage.imageOrientation) {
case UIImageOrientationDown:
case UIImageOrientationDownMirrored:
transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
transform = CGAffineTransformRotate(transform, M_PI);
break;
case UIImageOrientationLeft:
case UIImageOrientationLeftMirrored:
transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
transform = CGAffineTransformRotate(transform, M_PI_2);
break;
case UIImageOrientationRight:
case UIImageOrientationRightMirrored:
transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
transform = CGAffineTransformRotate(transform, -M_PI_2);
break;
default:
break;
}
switch (aImage.imageOrientation) {
case UIImageOrientationUpMirrored:
case UIImageOrientationDownMirrored:
transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
transform = CGAffineTransformScale(transform, -1, 1);
break;
case UIImageOrientationLeftMirrored:
case UIImageOrientationRightMirrored:
transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
transform = CGAffineTransformScale(transform, -1, 1);
break;
default:
break;
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
CGImageGetBitsPerComponent(aImage.CGImage), 0,
CGImageGetColorSpace(aImage.CGImage),
CGImageGetBitmapInfo(aImage.CGImage));
CGContextConcatCTM(ctx, transform);
switch (aImage.imageOrientation) {
case UIImageOrientationLeft:
case UIImageOrientationLeftMirrored:
case UIImageOrientationRight:
case UIImageOrientationRightMirrored:
CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
break;
default:
CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
break;
}
// And now we just create a new UIImage from the drawing context
CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
UIImage *img = [UIImage imageWithCGImage:cgimg];
CGContextRelease(ctx);
CGImageRelease(cgimg);
return img;
}
複制
自定義相機拍照視圖
定義變量
//捕獲裝置,通常是前置攝像頭,後置攝像頭,麥克風(音頻輸入)
@property (nonatomic, strong) AVCaptureDevice *device;
//AVCaptureDeviceInput 代表輸入裝置,他使用AVCaptureDevice 來初始化
@property (nonatomic, strong) AVCaptureDeviceInput *input;
//輸出圖檔
@property (nonatomic ,strong) AVCaptureStillImageOutput *imageOutput;
//session:由他把輸入輸出結合在一起,并開始啟動捕獲裝置(攝像頭)
@property (nonatomic, strong) AVCaptureSession *session;
//圖像預覽層,實時顯示捕獲的圖像
@property (nonatomic ,strong) AVCaptureVideoPreviewLayer *previewLayer;
@property (weak, nonatomic) IBOutlet UIView *previewView;
@property (weak, nonatomic) IBOutlet UIImageView *showImageView;
複制
設定相機
- (void)cameraDistrict{
// AVCaptureDevicePositionBack 後置攝像頭
// AVCaptureDevicePositionFront 前置攝像頭
self.device = [self cameraWithPosition:AVCaptureDevicePositionBack];
self.input = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:nil];
self.imageOutput = [[AVCaptureStillImageOutput alloc] init];
self.session = [[AVCaptureSession alloc] init];
// 拿到的圖像的大小可以自行設定
// AVCaptureSessionPreset320x240
// AVCaptureSessionPreset352x288
// AVCaptureSessionPreset640x480
// AVCaptureSessionPreset960x540
// AVCaptureSessionPreset1280x720
// AVCaptureSessionPreset1920x1080
// AVCaptureSessionPreset3840x2160
self.session.sessionPreset = AVCaptureSessionPreset640x480;
//輸入輸出裝置結合
if ([self.session canAddInput:self.input]) {
[self.session addInput:self.input];
}
if ([self.session canAddOutput:self.imageOutput]) {
[self.session addOutput:self.imageOutput];
}
//預覽層的生成
self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
self.previewLayer.frame = self.previewView.frame;
self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[self.previewView.layer addSublayer:self.previewLayer];
//裝置取景開始
[self.session startRunning];
if ([_device lockForConfiguration:nil]) {
//自動閃光燈,
if ([_device isFlashModeSupported:AVCaptureFlashModeAuto]) {
[_device setFlashMode:AVCaptureFlashModeAuto];
}
//自動白平衡,但是好像一直都進不去
if ([_device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
[_device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
}
[_device unlockForConfiguration];
}
}
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for ( AVCaptureDevice *device in devices )
if ( device.position == position ){
return device;
}
return nil;
}
複制
擷取相機圖檔
- (void)photoBtnDidClick{
AVCaptureConnection *conntion = [self.imageOutput connectionWithMediaType:AVMediaTypeVideo];
if (!conntion) {
NSLog(@"拍照失敗!");
return;
}
[self.imageOutput captureStillImageAsynchronouslyFromConnection:conntion completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
if (imageDataSampleBuffer == nil) {
return ;
}
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
self.showImageView.image = [UIImage imageWithData:imageData];
self.showImageView.hidden = false;
[self.session stopRunning];
}];
}
複制
儲存照片到相冊
#pragma - 儲存至相冊
- (void)saveImageToPhotoAlbum:(UIImage*)savedImage{
UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}
// 指定回調方法
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo{
NSString *msg = nil ;
if(error != NULL){
msg = @"儲存圖檔失敗" ;
}else{
msg = @"儲存圖檔成功" ;
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"儲存圖檔結果提示"
message:msg
delegate:self
cancelButtonTitle:@"确定"
otherButtonTitles:nil];
[alert show];
}
複制
前後置攝像頭的切換
- (void)changeCamera{
NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
if (cameraCount > 1) {
NSError *error;
//給攝像頭的切換添加翻轉動畫
CATransition *animation = [CATransition animation];
animation.duration = .5f;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animation.type = @"oglFlip";
AVCaptureDevice *newCamera = nil;
AVCaptureDeviceInput *newInput = nil;
//拿到另外一個攝像頭位置
AVCaptureDevicePosition position = [[_input device] position];
if (position == AVCaptureDevicePositionFront){
newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
animation.subtype = kCATransitionFromLeft;//動畫翻轉方向
}
else {
newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
animation.subtype = kCATransitionFromRight;//動畫翻轉方向
}
//生成新的輸入
newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
[self.previewLayer addAnimation:animation forKey:nil];
if (newInput != nil) {
[self.session beginConfiguration];
[self.session removeInput:self.input];
if ([self.session canAddInput:newInput]) {
[self.session addInput:newInput];
self.input = newInput;
} else {
[self.session addInput:self.input];
}
[self.session commitConfiguration];
} else if (error) {
NSLog(@"toggle carema failed, error = %@", error);
}
}
}
複制
對焦設定
//AVCaptureFlashMode 閃光燈
//AVCaptureFocusMode 對焦
//AVCaptureExposureMode 曝光
//AVCaptureWhiteBalanceMode 白平衡
//閃光燈和白平衡可以在生成相機時候設定
//曝光要根據對焦點的光線狀況而決定,是以和對焦一塊寫
//point為點選的位置
- (void)focusAtPoint:(CGPoint)point{
CGSize size = self.view.bounds.size;
CGPoint focusPoint = CGPointMake( point.y /size.height ,1-point.x/size.width );
NSError *error;
if ([self.device lockForConfiguration:&error]) {
//對焦模式和對焦點
if ([self.device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
[self.device setFocusPointOfInterest:focusPoint];
[self.device setFocusMode:AVCaptureFocusModeAutoFocus];
}
//曝光模式和曝光點
if ([self.device isExposureModeSupported:AVCaptureExposureModeAutoExpose ]) {
[self.device setExposurePointOfInterest:focusPoint];
[self.device setExposureMode:AVCaptureExposureModeAutoExpose];
}
[self.device unlockForConfiguration];
//設定對焦動畫
// _focusView.center = point;
// _focusView.hidden = NO;
// [UIView animateWithDuration:0.3 animations:^{
// _focusView.transform = CGAffineTransformMakeScale(1.25, 1.25);
// }completion:^(BOOL finished) {
// [UIView animateWithDuration:0.5 animations:^{
// _focusView.transform = CGAffineTransformIdentity;
// } completion:^(BOOL finished) {
// _focusView.hidden = YES;
// }];
// }];
}
}
複制
遇到的一些坑和解決辦法
前後置攝像頭的切換
前後值不能切換,各種嘗試找了半天沒找到有原因。後來發現我在設定圖檔尺寸的時候設定為1080P
[self.session canSetSessionPreset: AVCaptureSessionPreset1920x1080]
,前置攝像頭并不支援這麼大的尺寸,是以就不能切換前置攝像頭。
我驗證了下 前置攝像頭最高支援720P,720P以内可自由切換。
當然也可以在前後置攝像頭切換的時候,根據前後攝像頭來設定不同的尺寸,這裡不在贅述。
焦點位置
CGPoint focusPoint = CGPointMake( point.y /size.height ,1-point.x/size.width );
複制
setExposurePointOfInterest:focusPoint
函數後面Point取值範圍是取景框左上角(0,0)到取景框右下角(1,1)之間。官方是這麼寫的:
The value of this property is a CGPoint that determines the receiver's focus point of interest, if it has one. A value of (0,0) indicates that the camera should focus on the top left corner of the image, while a value of (1,1) indicates that it should focus on the bottom right. The default value is (0.5,0.5).
複制
我也試了按這個來但位置就是不對,隻能按上面的寫法才可以。前面是點選位置的y/PreviewLayer的高度,後面是1-點選位置的x/PreviewLayer的寬度
複制
對焦和曝光
我在設定
對焦
是 先設定了模式setFocusMode,後設定對焦位置,就會導緻很奇怪的現象,對焦位置是你上次點選的位置。是以一定要先設定位置,再設定對焦模式。
曝光
同上