GPUImage源碼分析與使用(三)

使用GPUImage拍照添加濾鏡

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //拍照添加濾鏡
    //1.添加按鈕拍照
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake((self.view.bounds.size.width-80)*0.5, self.view.bounds.size.height-120, 80, 40);
    button.backgroundColor = [UIColor blueColor];
    [button setTitle:@"拍照" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(takePhoto) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    [self.view bringSubviewToFront:button];
    
    //2.照相機添加濾鏡
    [self addFilterCamera];
}

- (void)addFilterCamera {
    //1.獲取照相機请垛,AVCaptureSessionPreset640x480照片尺寸叨粘,AVCaptureDevicePositionFront前置攝像頭
    _sCamera = [[GPUImageStillCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionFront];
    
    //2.切換攝像頭
    [_sCamera rotateCamera];
    
    //3.豎屏
    _sCamera.outputImageOrientation = UIInterfaceOrientationPortrait;
    
    //4.初始化濾鏡---灰度濾鏡
    _grayFilter = [[GPUImageGrayscaleFilter alloc] init];
    [_sCamera addTarget:_grayFilter];
    
    //5.顯示在GPUImageView
    _gpuImageView = [[GPUImageView alloc] initWithFrame:self.jingImageView.frame];
    [_grayFilter addTarget:_gpuImageView];
    
    [self.view addSubview:_gpuImageView];
    
    //6.開始拍照
    [_sCamera startCameraCapture];
    
    
}

- (void)takePhoto {
    //7.拍照后處理照片橙数,添加相冊
    [_sCamera capturePhotoAsJPEGProcessedUpToFilter:_grayFilter withCompletionHandler:^(NSData *processedJPEG, NSError *error) {
        
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            [[PHAssetCreationRequest creationRequestForAsset] addResourceWithType:PHAssetResourceTypePhoto data:processedJPEG options:nil];
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            
        }];
        
        //獲取拍攝的圖片預覽
        UIImage *newImage = [UIImage imageWithData:processedJPEG];
        
        [self.view bringSubviewToFront:self.jingImageView];
        self.jingImageView.image = newImage;
    }];
    
}

使用GPUImage拍視頻添加濾鏡

VideoManager.h

@protocol videoDelegate <NSObject>

- (void)didStartRecordVideo;

- (void)didCompressingVideo;

- (void)didEndRecordVideoWithTime:(CGFloat)totalTime outputFile:(NSString *)filePath;

@end

@interface VideoManager : NSObject

@property (nonatomic, assign) CGRect frame;
@property (nonatomic, weak) id<videoDelegate> delegate;

- (void)showWithFrame:(CGRect *)rect superView:(UIView *)view;

- (void)startRecording;
- (void)stopRecording;

@end

VideoManager.m

//視頻錄制單例
+ (instancetype)manager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[VideoManager alloc] init];
    });
    return _manager;
}

//開始錄制
- (void)startRecording {
    //錄制路徑
    NSString *defaultPath = [self getVideoPathCache];
    self.moviePath = [defaultPath stringByAppendingPathComponent:[self getVideoNameWithType:@"mp4"]];
    self.movieUrl = [NSURL fileURLWithPath:self.moviePath];
    
    self.movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:self.movieUrl size:CGSizeMake(480, 640)];
    self.movieWriter.encodingLiveVideo = YES;
    self.movieWriter.shouldPassthroughAudio = YES;
    
    [self.saturationFilter addTarget:self.movieWriter];
    
    self.videoCamera.audioEncodingTarget = self.movieWriter;
    
    //開始錄制
    [self.movieWriter startRecording];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(didStartRecordVideo)]) {
        [self.delegate didStartRecordVideo];
    }
    [self.timer setFireDate:[NSDate distantPast]];
    [self.timer fire];
}

//結(jié)束錄制
- (void)stopRecording {
    if (self.videoCamera) {
        
        [self.timer invalidate];
        self.timer = nil;
        
        [self.movieWriter finishRecording];
        
        //移除濾鏡
        [self.saturationFilter removeTarget:self.movieWriter];
        
        self.videoCamera.audioEncodingTarget = nil;
        
        if (self.recordSecond > self.maxTime) {
            //可以清除錄制的內(nèi)容
        }else {
            //壓縮視頻
            if (self.delegate && [self.delegate respondsToSelector:@selector(didCompressingVideo)]) {
                [self.delegate didCompressingVideo]; //提示正在壓縮
            }
            
            //開始壓縮
            __weak typeof(self) weakSelf = self;
            [self compressVideoWithUrl:self.movieUrl compressionType:AVAssetExportPresetMediumQuality filePath:^(NSString *resultPath, float memorySize, NSString *videoImagePath, int seconds){
                
                NSData *data = [NSData dataWithContentsOfFile:resultPath];
                CGFloat totalTime = (CGFloat)data.length/1024/1024;
                
                if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(didEndRecordVideoWithTime:outputFile:)]) {
                    [weakSelf.delegate didEndRecordVideoWithTime:totalTime outputFile:resultPath];
                }
            }];
        }
    }
}

- (void)compressVideoWithUrl:(NSURL *)url compressionType:(NSString *)type filePath:(void(^)(NSString *resultPath, float memorySize, NSString *videoImagePath, int seconds))resultBlock {
    
    NSString *resultPath;
    
    // 視頻壓縮前大小
    NSData *data = [NSData dataWithContentsOfURL:url];
    CGFloat totalSize = (float)data.length / 1024 / 1024;
    NSLog(@"壓縮前大斜枳纭:%.2fM",totalSize);
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil];
    
    CMTime time = [avAsset duration];
    
    // 視頻時長
    int seconds = ceil(time.value / time.timescale);
    
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    if ([compatiblePresets containsObject:type]) {
        
        // 中等質(zhì)量
        AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
        
        // 用時間給文件命名 防止存儲被覆蓋
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
        
        // 若壓縮路徑不存在重新創(chuàng)建
        NSFileManager *manager = [NSFileManager defaultManager];
        BOOL isExist = [manager fileExistsAtPath:COMPRESSEDVIDEOPATH];
        if (!isExist) {
            [manager createDirectoryAtPath:COMPRESSEDVIDEOPATH withIntermediateDirectories:YES attributes:nil error:nil];
        }
        resultPath = [COMPRESSEDVIDEOPATH stringByAppendingPathComponent:[NSString stringWithFormat:@"user%outputVideo-%@.mp4",arc4random_uniform(10000),[formatter stringFromDate:[NSDate date]]]];
        
        session.outputURL = [NSURL fileURLWithPath:resultPath];
        session.outputFileType = AVFileTypeMPEG4;
        session.shouldOptimizeForNetworkUse = YES;
        [session exportAsynchronouslyWithCompletionHandler:^{
            
            switch (session.status) {
                case AVAssetExportSessionStatusUnknown:
                    break;
                case AVAssetExportSessionStatusWaiting:
                    break;
                case AVAssetExportSessionStatusExporting:
                    break;
                case AVAssetExportSessionStatusCancelled:
                    break;
                case AVAssetExportSessionStatusFailed:
                    break;
                case AVAssetExportSessionStatusCompleted:{
                    
                    NSData *data = [NSData dataWithContentsOfFile:resultPath];
                    // 壓縮過后的大小
                    float compressedSize = (float)data.length / 1024 / 1024;
                    resultBlock(resultPath,compressedSize,@"",seconds);
                    NSLog(@"壓縮后大械馍摇:%.2f",compressedSize);
                }
                default:
                    break;
            }
        }];
    }
}

- (void)showWithFrame:(CGRect)frame superView:(UIView *)superView {
    _frame = frame;
    [self.saturationFilter addTarget:self.displayView];
    [self.videoCamera addTarget:self.saturationFilter];
    
    [superView addSubview:self.displayView];
    [self.videoCamera startCameraCapture];
}

#pragma mark - 攝像頭輸出
- (void)willOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer {
    //返回已經(jīng)添加濾鏡的sampleBuffer
}

VideoViewController.m

- (void)setupVideoManager {
    _manager = [[VideoManager alloc] init];
    _manager.delegate = self;
    [_manager showWithFrame:CGRectMake(20, 120, LMW, LMH) superView:self.view];
    
}

- (void)shootVideo {
    [_manager startRecording];
}

- (void)stopVideo {
    [_manager stopRecording];
}

- (void)playVideo {
    _player = [[AVPlayerViewController alloc] init];
    _player.player = [[AVPlayer alloc] initWithURL:[NSURL fileURLWithPath:_filePath]];
    _player.videoGravity = AVLayerVideoGravityResizeAspect;
    [self presentViewController:_player animated:NO completion:nil];
}

- (void)didStartRecordVideo {
    NSLog(@"開始錄制");
}

- (void)didCompressingVideo {
    NSLog(@"視頻壓縮中");
}

- (void)didEndRecordVideoWithTime:(CGFloat)totalTime outputFile:(NSString *)filePath {
    NSLog(@"錄制完畢---%f秒甘晤,%@", totalTime, filePath);
    _filePath = filePath;
}
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末乳绕,一起剝皮案震驚了整個濱河市享潜,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌基协,老刑警劉巖歌亲,帶你破解...
    沈念sama閱讀 206,968評論 6 482
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異澜驮,居然都是意外死亡陷揪,警方通過查閱死者的電腦和手機芜茵,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,601評論 2 382
  • 文/潘曉璐 我一進店門肠槽,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人姑荷,你說我怎么就攤上這事耐量》沈荆” “怎么了?”我有些...
    開封第一講書人閱讀 153,220評論 0 344
  • 文/不壞的土叔 我叫張陵廊蜒,是天一觀的道長趴拧。 經(jīng)常有香客問我,道長山叮,這世上最難降的妖魔是什么著榴? 我笑而不...
    開封第一講書人閱讀 55,416評論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮聘芜,結(jié)果婚禮上兄渺,老公的妹妹穿的比我還像新娘。我一直安慰自己汰现,他們只是感情好挂谍,可當我...
    茶點故事閱讀 64,425評論 5 374
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著瞎饲,像睡著了一般口叙。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上嗅战,一...
    開封第一講書人閱讀 49,144評論 1 285
  • 那天妄田,我揣著相機與錄音,去河邊找鬼驮捍。 笑死疟呐,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的东且。 我是一名探鬼主播启具,決...
    沈念sama閱讀 38,432評論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼珊泳!你這毒婦竟也來了鲁冯?” 一聲冷哼從身側(cè)響起拷沸,我...
    開封第一講書人閱讀 37,088評論 0 261
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎薯演,沒想到半個月后撞芍,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,586評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡跨扮,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,028評論 2 325
  • 正文 我和宋清朗相戀三年序无,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片衡创。...
    茶點故事閱讀 38,137評論 1 334
  • 序言:一個原本活蹦亂跳的男人離奇死亡愉镰,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出钧汹,到底是詐尸還是另有隱情,我是刑警寧澤录择,帶...
    沈念sama閱讀 33,783評論 4 324
  • 正文 年R本政府宣布拔莱,位于F島的核電站,受9級特大地震影響隘竭,放射性物質(zhì)發(fā)生泄漏塘秦。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,343評論 3 307
  • 文/蒙蒙 一动看、第九天 我趴在偏房一處隱蔽的房頂上張望尊剔。 院中可真熱鬧,春花似錦菱皆、人聲如沸须误。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,333評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽京痢。三九已至,卻和暖如春篷店,著一層夾襖步出監(jiān)牢的瞬間祭椰,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,559評論 1 262
  • 我被黑心中介騙來泰國打工疲陕, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留方淤,地道東北人。 一個月前我還...
    沈念sama閱讀 45,595評論 2 355
  • 正文 我出身青樓蹄殃,卻偏偏與公主長得像携茂,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子窃爷,可洞房花燭夜當晚...
    茶點故事閱讀 42,901評論 2 345

推薦閱讀更多精彩內(nèi)容