美文网首页
使用GPUImage给视频添加水印

使用GPUImage给视频添加水印

作者: 819e6e93a666 | 来源:发表于2017-12-06 11:01 被阅读0次
    - (void)addWaterMark {
        /* 使用GUPImage添加水印,原理上相当于添加一层滤镜  */
        
        NSURL *videoURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"IMG_4400" ofType:@"m4v"]];
        _movieFile = [[GPUImageMovie alloc] initWithURL:videoURL];
    //    _movieFile.runBenchmark = YES;
        _movieFile.playAtActualSpeed = NO;
    
        // 获取视频的size,从而确定水印的位置
        AVAsset *asset = [AVAsset assetWithURL:videoURL];
        CGSize size = CGSizeZero;
        NSArray *tracks = [asset tracksWithMediaType:AVMediaTypeVideo];
        if (tracks.count > 0) {
            AVAssetTrack *videoTrack = tracks.firstObject;
            size = CGSizeMake(videoTrack.naturalSize.width, videoTrack.naturalSize.height);
        }
    
        // 文字水印(同理可添加图片)
        UILabel *label = [[UILabel alloc] init];
        label.text = @"@Ander";
        label.font = kFontFromPx(100);
        label.textColor = kColorWithRGB(0xFFFFFF);
        label.textAlignment = NSTextAlignmentCenter;
        [label sizeToFit];
        label.frame = CGRectMake(size.width - label.size.width - 20, size.height - label.size.height - 20, label.size.width, label.size.height);
        // 将水印放在一个跟视频大小相等的View上
        UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
        [subView addSubview:label];
        
        _uiElement = [[GPUImageUIElement alloc] initWithView:subView];
        _blendFilter = [[GPUImageNormalBlendFilter alloc] init];
        GPUImageFilter* progressFilter = [[GPUImageFilter alloc] init];
        
        // 注意URL不要出错,不然下面会崩溃
        NSString *pathToMovie = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Movie.mp4"];
        unlink([pathToMovie UTF8String]);   // 删除当前该路径下的文件
        NSURL *movieURL = [NSURL fileURLWithPath:pathToMovie];
        
        _movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:movieURL size:size];
        [progressFilter addTarget:_blendFilter];
        [_movieFile addTarget:progressFilter];
        [_uiElement addTarget:_blendFilter];
        
        _movieWriter.shouldPassthroughAudio = YES;
        // 判断是否有音轨
        if ([asset tracksWithMediaType:AVMediaTypeAudio].count > 0){
            _movieFile.audioEncodingTarget = _movieWriter;
        } else {
            _movieFile.audioEncodingTarget = nil;
        }
        [_movieFile enableSynchronizedEncodingUsingMovieWriter:_movieWriter];
        [_blendFilter addTarget:_movieWriter];
        
        [_movieWriter startRecording];
        [_movieFile startProcessing];
        __weak typeof(self) weakSelf = self;
        //渲染
        [progressFilter setFrameProcessingCompletionBlock:^(GPUImageOutput *output, CMTime time) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //水印可以移动
                CGRect frame = label.frame;
                frame.origin.x -= 1;
                frame.origin.y -= 1;
                label.frame = frame;
                //第5秒之后隐藏coverImageView2
                if (time.value/time.timescale>=5.0) {
                    [label removeFromSuperview];
                }
            });
            // 这句必须有
            [weakSelf.uiElement update];
        }];
    
        [_movieWriter setCompletionBlock:^{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                __strong typeof(self) strongSelf = weakSelf;
                [strongSelf.blendFilter removeTarget:strongSelf.movieWriter];
                [strongSelf.movieWriter finishRecording];
                //保存相册
                __block PHObjectPlaceholder *placeholder;
                if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
                    if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(pathToMovie)) {
                        NSError *error;
                        [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
                            PHAssetChangeRequest* createAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:movieURL];
                            placeholder = [createAssetRequest placeholderForCreatedAsset];
                        } error:&error];
                        if (error) {
                            kShowPopTip(nil, error.description, nil);
                        }else {
                            kShowPopTip(nil, @"视频已保存到相册", nil);
                        }
                    }
                }
            });
        }];
    }
    

    参考文章:
    http://www.hudongdong.com/ios/546.html

    相关文章

      网友评论

          本文标题:使用GPUImage给视频添加水印

          本文链接:https://www.haomeiwen.com/subject/zcskixtx.html