公司新聞視頻直播需要添加實時文字和gif水印辱魁,在網上看了下大部分都是基于GPUImage來處理的烟瞧,發(fā)現大部分添加水印都是靜態(tài)圖片,么有加載gif圖片水印的染簇。于是自己嘗試實現参滴,這里參考了落影l(fā)oyinglin給視頻添加水印的思路。
主要思路:
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];
//創(chuàng)建水印圖形
GPUImageUIElement *uiElement = [[GPUImageUIElement alloc] initWithView:contentView];
//創(chuàng)建濾鏡
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];
}];
如果有更加好的思路脆诉,希望告知,謝謝贷币!