利用GPUImage添加实时文字水印和gif图片水印

公司新闻视频直播需要添加实时文字和gif水印,在网上看了下大部分都是基于GPUImage来处理的,发现大部分添加水印都是静态图片,么有加载gif图片水印的。于是自己尝试实现,这里参考了落影loyinglin给视频添加水印的思路。

主要思路:

1、把gif图片中的每帧图片提取出来保存到数组中,用索引index记录当前帧的位置
2、再把每帧图片和文字转为GUPUIElement对象
3、在实时视频的filter中的setFrameProcessingCompletionBlock中去update,index++,当index等于帧数组count-1,重置为零。
这样就能看到水印为gif动图。

代码实现
GPUImageView *gpuImageView = (GPUImageView*)self.view;

GPUImageVideoCamera *videoCamera = [[GPUImageVideoCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionBack];

videoCamera.outputImageOrientation = UIInterfaceOrientationPortrait;
_videoCamera = videoCamera;

//添加时间戳水印和图片水印
UIView *contentView = [[UIView alloc] initWithFrame:self.view.bounds];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy年MM月dd日hh:mm:ss"];
NSDate *currentDate = [NSDate date];
NSString *timeString = [formatter stringFromDate:currentDate];

UILabel *timestampLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 300, 30)];
timestampLabel.text = timeString;
timestampLabel.textColor = [UIColor redColor];
[contentView addSubview:timestampLabel];

UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(10, 100, 300, 80)];



NSString *path = [[NSBundle mainBundle] pathForResource:@"dong.gif" ofType:nil] ;
NSData *imageData = [NSData dataWithContentsOfFile:path];
_gifImages = [NSArray array];
_gifImages = [UIImage yj_animatedGIFImagesWithData:imageData];
_duration = [UIImage yj_animatedGIFDurationWithData:imageData];
_currenIndex = 0;
imageV.image = _gifImages[_currenIndex];
[contentView addSubview:imageV];


//创建水印图形
GPUImageUIElement *uiElement = [[GPUImageUIElement alloc] initWithView:contentView];



//创建滤镜
GPUImageDissolveBlendFilter *filter = [[GPUImageDissolveBlendFilter alloc] init];
filter.mix = 0.5;

GPUImageFilter *videoFilter = [[GPUImageFilter alloc] init];
[videoCamera addTarget:videoFilter];

[videoFilter addTarget:filter];
[uiElement addTarget:filter];

// 添加滤镜

[filter addTarget:gpuImageView];

[videoCamera startCameraCapture];

// 这句代码很重要,没有的话不会更新
[videoFilter setFrameProcessingCompletionBlock:^(GPUImageOutput *output, CMTime time) {
   
    
//        CGRect frame =  imageV.frame;
//        frame.origin.x += 1;
//        frame.origin.y += 1;
//         imageV.frame = frame;
    

    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy年MM月dd日hh:mm:ss"];
    NSDate *currentDate = [NSDate date];
    NSString *timeString = [formatter stringFromDate:currentDate];
    timestampLabel.text = timeString;
    
    
    _currenIndex ++;
    imageV.image = _gifImages[_currenIndex];
    
    if (_currenIndex == _gifImages.count -1) {
        
        _currenIndex = 0;
    }
    
    [uiElement update];
    
}];

如果有更加好的思路,希望告知,谢谢!

你可能感兴趣的:(利用GPUImage添加实时文字水印和gif图片水印)