美文网首页
iOS 视频图片添加文字水印

iOS 视频图片添加文字水印

作者: andy桐 | 来源:发表于2019-05-22 17:56 被阅读0次

    最近项目中遇到在拍视频和图片(类似微信发朋友圈那种)之后添加水印的需求,此处记录相关代码

    //self.fileNameString    //类似这种20190522175147-部门-姓名-地址,需求是把地址作为水印内容
    
    #define degreesToRadians( degrees ) ( ( degrees ) / 180.0 * M_PI )
    #define textLabelHeight 300
    #define textLabelFontSize 40
    
    - (void)addWaterTextWithVideoPath:(NSString*)path complete:(void (^)(NSString *compressStr))complete{
        //1 创建AVAsset实例
        AVURLAsset*videoAsset = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:path]];
        
        AVMutableComposition *mixComposition = [[AVMutableComposition alloc] init];
        
        //3 视频通道
        AVMutableCompositionTrack *videoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo
                                                                            preferredTrackID:kCMPersistentTrackID_Invalid];
        [videoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration)
                            ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeVideo] firstObject]
                             atTime:kCMTimeZero error:nil];
        
        //2 音频通道
        AVMutableCompositionTrack *audioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio
                                                                            preferredTrackID:kCMPersistentTrackID_Invalid];
        [audioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration)
                            ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeAudio] firstObject]
                             atTime:kCMTimeZero error:nil];
        
        //3.1 AVMutableVideoCompositionInstruction 视频轨道中的一个视频,可以缩放、旋转等
        AVMutableVideoCompositionInstruction *mainInstruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
        mainInstruction.timeRange = CMTimeRangeMake(kCMTimeZero, videoAsset.duration);
        
        // 3.2 AVMutableVideoCompositionLayerInstruction 一个视频轨道,包含了这个轨道上的所有视频素材
        AVMutableVideoCompositionLayerInstruction *videolayerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoTrack];
        
        [videolayerInstruction setOpacity:0.0 atTime:videoAsset.duration];
        //AVMutableVideoComposition:管理所有视频轨道,水印添加就在这上面
        AVMutableVideoComposition *mainCompositionInst = [AVMutableVideoComposition videoComposition];
        
        //视频旋转处理
        CGAffineTransform t1 = CGAffineTransformMakeTranslation(videoTrack.naturalSize.height, 0.0);
        // Rotate transformation
        CGAffineTransform  t2 = CGAffineTransformRotate(t1, degreesToRadians(90.0));
        [videolayerInstruction setTransform:t2 atTime:kCMTimeZero];
        
        // 3.3 - Add instructions
        mainInstruction.layerInstructions = [NSArray arrayWithObjects:videolayerInstruction,nil];
        
        
        AVAssetTrack *videoAssetTrack = [[videoAsset tracksWithMediaType:AVMediaTypeVideo] firstObject];
    //    CGSize naturalSize = videoAssetTrack.naturalSize;
        CGSize naturalSize = CGSizeMake(videoAssetTrack.naturalSize.height, videoAssetTrack.naturalSize.width);
        
        float renderWidth, renderHeight;
        renderWidth = naturalSize.width;
        renderHeight = naturalSize.height;
        mainCompositionInst.renderSize = CGSizeMake(renderWidth, renderHeight);
        mainCompositionInst.instructions = [NSArray arrayWithObject:mainInstruction];
        mainCompositionInst.frameDuration = CMTimeMake(1, 30);
        [self applyVideoEffectsToComposition:mainCompositionInst size:naturalSize];
        
        //    // 4 - 输出路径
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *myPathDocs =  [documentsDirectory stringByAppendingPathComponent:
                                 [NSString stringWithFormat:@"%@.mp4",self.fileNameString]];
        //判断文件是否存在,如果已经存在删除
        [[NSFileManager defaultManager] removeItemAtPath:myPathDocs error:nil];
        NSURL* videoUrl = [NSURL fileURLWithPath:myPathDocs];
        
        // 5 - 视频文件输出
        AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:mixComposition
                                                                          presetName:AVAssetExportPresetHighestQuality];
        exporter.outputURL = videoUrl;
        exporter.outputFileType = AVFileTypeMPEG4;
        exporter.shouldOptimizeForNetworkUse = YES;
        exporter.videoComposition = mainCompositionInst;
        [exporter exportAsynchronouslyWithCompletionHandler:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                if( exporter.status == AVAssetExportSessionStatusCompleted ){
                    NSLog(@"导出完成");
                    NSURL *compressURL = exporter.outputURL;
                    NSLog(@"导出完毕,导出后大小 %f MB",[self ytfileSize:compressURL]);
                    NSString *compressUrlStr = compressURL.absoluteString;
                    if ([compressUrlStr containsString:@"file://"]) {
                        compressUrlStr = [compressUrlStr substringFromIndex:7];
                    }
                    complete(compressUrlStr);
                }else if( exporter.status == AVAssetExportSessionStatusFailed ){
                    NSLog(@"导出failed");
                    complete(nil);
                }
            });
        }];
    }
    
    - (void)applyVideoEffectsToComposition:(AVMutableVideoComposition *)composition size:(CGSize)size
    {
        // 文字
        CATextLayer *subtitle1Text = [[CATextLayer alloc] init];
    //    [subtitle1Text setFont:@"Helvetica-Bold"];
        [subtitle1Text setFontSize:textLabelFontSize];
        subtitle1Text.wrapped = YES;//自动换行
        [subtitle1Text setFrame:CGRectMake(10, size.height-10-textLabelHeight, size.width-20, textLabelHeight)];
        [subtitle1Text setString:[self cutAddressFromFileName]];
    //    [subtitle1Text setAlignmentMode:kCAAlignmentCenter];
        [subtitle1Text setForegroundColor:[[UIColor whiteColor] CGColor]];
        
        //图片
    //    CALayer*picLayer = [CALayer layer];
    //    picLayer.contents = (id)[UIImage imageNamed:@"videoWater2"].CGImage;
    //    picLayer.frame = CGRectMake(size.width-15-87, 15, 87, 26);
        
        // 2 - The usual overlay
        CALayer *overlayLayer = [CALayer layer];
    //    [overlayLayer addSublayer:picLayer];
        [overlayLayer addSublayer:subtitle1Text];
        overlayLayer.frame = CGRectMake(0, 0, size.width, size.height);
        [overlayLayer setMasksToBounds:YES];
        
        CALayer *parentLayer = [CALayer layer];
        CALayer *videoLayer = [CALayer layer];
        parentLayer.frame = CGRectMake(0, 0, size.width, size.height);
        videoLayer.frame = CGRectMake(0, 0, size.width, size.height);
        [parentLayer addSublayer:videoLayer];
        [parentLayer addSublayer:overlayLayer];
        
        composition.animationTool = [AVVideoCompositionCoreAnimationTool videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:videoLayer inLayer:parentLayer];
    }
    
    -(NSString *)cutAddressFromFileName{
        NSString *addressStr = @"test";
        if ([self.fileNameString containsString:@"-"]) {
            NSArray *infoArr = [self.fileNameString componentsSeparatedByString:@"-"];
            addressStr = (NSString *)infoArr.lastObject;
        }
        return addressStr;
    }
    
    //计算文件大小
    -(CGFloat)ytfileSize:(NSURL *)path{
        return [[NSData dataWithContentsOfURL:path] length]/1024.00 /1024.00;
    }
    
    //给图片添加文字水印
    -(UIImage *)imageWithimage:(UIImage *)image content:(NSString *)content frame:(CGRect)frame {
        // 开启图形'上下文'
        UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
        // 绘制原生图片
        [image drawAtPoint:CGPointZero];
        // 在原生图上绘制文字
        NSString *str = content;
        // 创建文字属性字典
        NSDictionary *dictionary = @{NSForegroundColorAttributeName: [UIColor whiteColor], NSFontAttributeName: [UIFont systemFontOfSize:textLabelFontSize]};
        // 绘制文字属性
        [str drawInRect:frame withAttributes:dictionary];
        // 从当前上下文获取修改后的图片
        UIImage *imageNew = UIGraphicsGetImageFromCurrentImageContext();
        // 结束图形上下文
        UIGraphicsEndImageContext();
        return imageNew;
    }
    

    后续有时间再记录微信发朋友圈拍摄页面代码

    补充:2020.7.3
    最近同事出现一个问题,文字水印有的时候不显示,后来还是他自己找到了解决方法:
    在CATextLayer属性设置都OK后调用display方法

    [subtitle1Text display];
    

    测试有效,感谢我牛逼的同事

    相关文章

      网友评论

          本文标题:iOS 视频图片添加文字水印

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