上一篇中我們成功地將拍攝到的錄像保存到了相冊(cè)。還差另一個(gè)功能,對(duì)了,拍照。
7月31日更新
上次的代碼有些問題,漏了一句釋放方法,會(huì)導(dǎo)致內(nèi)存泄露。在willOutputSampleBuffer:第三段代碼上方某處加入
CGImageRelease(sourceCGImage);
即可。詳見修改過的代碼。
GPUImage庫里面有個(gè)still camera的類,然而如果想同時(shí)打開拍照和攝像的2個(gè)攝像頭實(shí)例是不可行的,而且,豈不是很浪費(fèi)系統(tǒng)資源?那么如何用攝像的camera實(shí)例來拍攝靜態(tài)照片呢?
什么?你說你可以只按0.1秒?
嚴(yán)肅點(diǎn),下面我們開始正文了。
打開那個(gè)工程,對(duì),你知道是哪個(gè)。
在ViewController.h中聲明該類實(shí)現(xiàn)GPUImageVideoCameraDelegate的協(xié)議。
-
在ViewController.m中viewDidLoad方法中的第一段代碼最后聲明代理。
_videoCamera.delegate = self;
-
在實(shí)現(xiàn)delegate方法前,先到.h設(shè)置幾個(gè)成員變量吧。
BOOL _willCapturePicture; CIContext *_ciContext; CGRect _sourceRect;
-
willOutputSampleBuffer:這個(gè)方法在AVFoundation里面也有提供,很多基于AVFoundation的擴(kuò)展庫都會(huì)保留這個(gè)方法用于對(duì)幀畫面的手動(dòng)處理。它會(huì)在捕獲每一幀畫面的時(shí)候被調(diào)用,此時(shí)可以對(duì)畫面進(jìn)行一些處理。這里我們用_willCapturePicture判斷是否要保存當(dāng)前幀。
實(shí)現(xiàn)代碼如下:- (void)willOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer { // 1. Do nothing if didn't press capture button if (!_willCapturePicture) { return; } // 2. Transfer sample buffer to image CVPixelBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); CVPixelBufferLockBaseAddress(imageBuffer, 0); CIImage *sourceImage = [CIImage imageWithCVPixelBuffer:imageBuffer options:nil]; UIGraphicsBeginImageContext(sourceImage.extent.size); // Source image的大小獲取一次就可以了,為了性能考慮,把這個(gè)尺寸存到類成員里面 static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _sourceRect = sourceImage.extent; }); CGContextRef context = UIGraphicsGetCurrentContext(); CGImageRef sourceCGImage = [_ciContext createCGImage:sourceImage fromRect:_sourceRect]; // 由于攝像頭的坐標(biāo)系和UI和Core Graphics都不一樣,需要把坐標(biāo)系轉(zhuǎn)換一下 CGAffineTransform transform = CGAffineTransformIdentity; transform = CGAffineTransformMakeTranslation(0, _sourceRect.size.height); transform = CGAffineTransformScale(transform, 1, -1); CGContextConcatCTM(context, transform); CGContextDrawImage(context, _sourceRect, sourceCGImage); CGImageRelease(sourceCGImage);// 千萬不能忘了釋放內(nèi)存 UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); // 3. Take a photo if (_willCapturePicture) { UIGraphicsBeginImageContext(CGSizeMake(resultImage.size.height, resultImage.size.width)); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextRotateCTM(context, M_PI_2); CGContextTranslateCTM(context, 0, -resultImage.size.height); [resultImage drawAtPoint:CGPointZero]; UIImage *resultImage2 = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); // 加濾鏡。這里獲得的圖片是原始攝像頭捕獲的畫面,需要手動(dòng)加一下濾鏡效果。 GPUImagePicture *stillImageSource = [[GPUImagePicture alloc] initWithImage:resultImage2]; [stillImageSource addTarget:_filter]; [_filter useNextFrameForImageCapture]; [stillImageSource processImage]; UIImage *currentFilteredVideoFrame = [_filter imageFromCurrentFramebuffer]; NSData *processedJPEG = UIImageJPEGRepresentation(currentFilteredVideoFrame, 1); ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; [library writeImageDataToSavedPhotosAlbum:processedJPEG metadata:nil completionBlock:^(NSURL *assetURL, NSError *error2) { if (error2) { NSLog(@"ERROR: the image failed to be written"); } else { NSLog(@"PHOTO SAVED - assetURL: %@", assetURL); } }]; _willCapturePicture = NO; } CVPixelBufferUnlockBaseAddress(imageBuffer, 0); }
這段代碼很長(zhǎng),大致就是把CMSampleBufferRef進(jìn)行一系列類型轉(zhuǎn)換和坐標(biāo)系變換,轉(zhuǎn)成我們熟悉的UIImage然后轉(zhuǎn)成NSData然后保存到相冊(cè)。
第二段代碼里面把坐標(biāo)系轉(zhuǎn)換以后獲取了當(dāng)前的CGContext,并在上面畫了一層CGImage。這段代碼寫那么復(fù)雜是為之后另一個(gè)功能做準(zhǔn)備的。
拍攝操作主要還是在第三段代碼,把當(dāng)前獲取的sample buffer轉(zhuǎn)成的UIImage保存到相冊(cè)里面。
-
好了,主要功能寫完,剩下只要添加調(diào)用的代碼就行了。到viewDidLoad中找到第五段代碼,在末尾加上以下代碼:
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)]; [_captureButton addGestureRecognizer:tapGesture]; // 6. Other setup EAGLContext *eaglContext = [[EAGLContext alloc]initWithAPI:kEAGLRenderingAPIOpenGLES2]; _ciContext = [CIContext contextWithEAGLContext:eaglContext];
這里用EAGLContext來初始化CIContext因?yàn)镋AGLContext創(chuàng)建以后是GPU來進(jìn)行操作,比CPU快很多。
-
到handleGesture:方法最后加上另一個(gè)手勢(shì)的處理:
else if ([sender isKindOfClass:[UITapGestureRecognizer class]]) { UITapGestureRecognizer *tapGesture = (UITapGestureRecognizer *)sender; switch (tapGesture.state) { case UIGestureRecognizerStateEnded: { _willCapturePicture = YES; } break; default: break; } }
到這里我們又實(shí)現(xiàn)了照片拍攝。當(dāng)然照片不會(huì)像專職照片相機(jī)這么清晰,無奈也是一種妥協(xié)了。因?yàn)槿绻麛z像頭尺寸調(diào)到1920x1080,實(shí)時(shí)畫面處理對(duì)于iPhone6來說性能也是不夠的。所以這個(gè)相機(jī)demo不是為了拍美景的,主要用于社交、美顏、文藝青年的使用場(chǎng)景。小尺寸便于分享傳輸、節(jié)約網(wǎng)絡(luò)流量。
這次的代碼非常復(fù)雜,但很多都是搬磚操作,仔細(xì)閱讀以后不會(huì)覺得像想象中這么深?yuàn)W。我當(dāng)初倒是為了坐標(biāo)系變換調(diào)試了很久。有任何代碼上面的問題請(qǐng)不要猶豫,在下方留言。