#import ?<Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "GPUImage.h"
@property (nonatomic, strong) GPUImageMovie *movieFile;
@property (nonatomic, strong) GPUImageMovieWriter? ? ? *movieWriter;
@property (nonatomic, strong) GPUImageNormalBlendFilter *filter;
//網(wǎng)絡(luò)視頻保存到本地
-(void)saveVideo{
?? ?dispatch_queue_t queue = dispatch_queue_create("hmj", DISPATCH_QUEUE_CONCURRENT);
? ? dispatch_async(queue, ^{
? ? ? ? NSLog(@"我是第一個(gè)任務(wù), 當(dāng)前線程:%@ ,是否主線程%d",[NSThread currentThread],[NSThread isMainThread]);
? ? ? ? NSString *filePath;
? ? ? ? NSDate *date = [NSDate date];
? ? ? ? NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.videoModel.videoUrl]];
? ? ? ? NSURLResponse *response;
? ? ? ? NSError *error;
? ? ? ? NSData* result = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
? ? ? ? NSLog(@"Response expects %lld bytes", [response expectedContentLength]);
? ? ? ? NSLog(@"Response suggested file name: %@", [response suggestedFilename]);
? ? ? ? if ([response suggestedFilename])
? ? ? ? ? ? //? ? ? ? ? ? self.savePath = [DEST_PATH stringByAppendingString:[response suggestedFilename]];
? ? ? ? ? ? if (!result)
? ? ? ? ? ? ? ? NSLog(@"Error downloading data: %@.", [error localizedDescription]);
? ? ? ? ? ? else if (response.expectedContentLength < 0)
? ? ? ? ? ? ? ? NSLog(@"Error with download. Carrier redirect?");
? ? ? ? ? ? else
? ? ? ? ? ? {
? ? ? ? ? ? ? ? NSLog(@"Download succeeded.");
? ? ? ? ? ? ? ? NSLog(@"Read %ld bytes", result.length);
? ? ? ? ? ? ? ? NSLog(@"Elapsed time: %0.2f seconds.", -1*[date timeIntervalSinceNow]);
? ? ? ? ? ? ? ? NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
? ? ? ? ? ? ? ? filePath = [NSString stringWithFormat:@"%@/video.mp4",docDirPath];
? ? ? ? ? ? ? ? if ([result writeToFile:filePath atomically:YES]) {
? ? ? ? ? ? ? ? ? ? NSLog(@"succeed");
? ? ? ? ? ? ? ? ? ? [self saveVideo:filePath];
? ? ? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? ? ? NSLog(@"faild");
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? });
}
//videoPath為視頻下載到本地之后的本地路徑
- (void)saveVideo:(NSString *)videoPath{
? ? if (videoPath) {
//加水印
? ? ? ? NSURL *videoURL = [NSURL fileURLWithPath:videoPath];
? ? ? ? [self saveVedioPath:videoURL WithWaterImg:[UIImage imageNamed:@"wylb"] WithCoverImage:[UIImage imageNamed:@"wylb"] WithQustion:[NSString stringWithFormat:@"令令號:%@",[LLManagerTool getUserRequireId]] WithFileName:@"waterVideo"];
//不加水印直接保存
//? ? ? ? if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(videoPath)) {
//? ? ? ? ? ? //保存相冊核心代碼
//? ? ? ? ? ? UISaveVideoAtPathToSavedPhotosAlbum(videoPath, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
//? ? ? ? }
? ? }
}
//不加水印
-(void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo: (void *)contextInfo{
? ? if (error) {
? ? ? ? NSLog(@"保存視頻失敗%@", error.localizedDescription);
? ? ? ? if (_isShowBlock) {
? ? ? ? ? ? _isShowBlock(NO,@"保存失敗",@"保存至相冊");
? ? ? ? }
? ? }
? ? else {
? ? ? ? NSLog(@"保存視頻成功");
? ? ? ? if (_isShowBlock) {
? ? ? ? ? ? _isShowBlock(NO,@"保存成功",@"保存至相冊");
? ? ? ? }
? ? }
}
//加水印保存在本地
-(void)saveVedioPath:(NSURL*)vedioPath WithWaterImg:(UIImage*)img WithCoverImage:(UIImage*)coverImg WithQustion:(NSString*)question WithFileName:(NSString*)fileName
{
? ? // 濾鏡
? ? //? ? filter = [[GPUImageDissolveBlendFilter alloc] init];
? ? //? ? [(GPUImageDissolveBlendFilter *)filter setMix:0.0f];
? ? //也可以使用透明濾鏡
? ? //? ? filter = [[GPUImageAlphaBlendFilter alloc] init];
? ? //? ? //mix即為疊加后的透明度,這里就直接寫1.0了
? ? //? ? [(GPUImageDissolveBlendFilter *)filter setMix:1.0f];
?? ?_filter = [[GPUImageNormalBlendFilter alloc] init];
? ? NSURL *sampleURL? = vedioPath;
? ? AVAsset *asset = [AVAsset assetWithURL:sampleURL];
? ? CGSize size = asset.naturalSize;
? ? _movieFile = [[GPUImageMovie alloc] initWithAsset:asset];
? ? _movieFile.playAtActualSpeed = NO;
? ? // 文字水印
? ? UILabel *label = [[UILabel alloc] init];
? ? label.text = question;
? ? label.font = [UIFont systemFontOfSize:15];
? ? label.textColor = [UIColor whiteColor];
? ? [label setTextAlignment:NSTextAlignmentRight];
? ? [label sizeToFit];
//? ? label.layer.masksToBounds = YES;
//? ? label.layer.cornerRadius = 18.0f;
? ? [label setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5]];
? ? [label setFrame:CGRectMake(SCREEN_WIDTH-label.size.width-20, SCREEN_HEIGHT-50, label.size.width, 20)];
? ? //圖片水印
? ? UIImage *coverImage1 = [img copy];
? ? UIImageView *coverImageView1 = [[UIImageView alloc] initWithImage:coverImage1];
? ? [coverImageView1 setFrame:CGRectMake(SCREEN_WIDTH - 131, SCREEN_HEIGHT-110, 111, 27)];
? ? //第二個(gè)圖片水印
? ? UIImage *coverImage2 = [coverImg copy];
? ? UIImageView *coverImageView2 = [[UIImageView alloc] initWithImage:coverImage2];
? ? [coverImageView2 setFrame:CGRectMake(270, 100, 210, 50)];
? ? UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
? ? subView.backgroundColor = [UIColor clearColor];
? ? [subView addSubview:coverImageView1];
//? ? [subView addSubview:coverImageView2];
? ? [subView addSubview:label];
? ? [coverImageView1 mas_makeConstraints:^(MASConstraintMaker *make) {
? ? ? ? make.left.top.offset(20);
? ? ? ? make.height.offset(20);
? ? ? ? make.width.offset(50);
? ? }];
? ? [label mas_makeConstraints:^(MASConstraintMaker *make) {
? ? ? ? make.top.equalTo(coverImageView1.mas_bottom).offset(10);
? ? ? ? make.left.offset(20);
? ? }];
? ? GPUImageUIElement *uielement = [[GPUImageUIElement alloc] initWithView:subView];
? ? NSString *pathToMovie = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/%@.mp4",fileName]];
? ? unlink([pathToMovie UTF8String]);
? ? NSURL *movieURL = [NSURL fileURLWithPath:pathToMovie];
? ? _movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:movieURL size:CGSizeMake(SCREEN_WIDTH , SCREEN_HEIGHT)];
? ? GPUImageFilter* progressFilter = [[GPUImageFilter alloc] init];
? ? [progressFilter addTarget:_filter];
? ? [_movieFile addTarget:progressFilter];
? ? [uielement addTarget:_filter];
? ? _movieWriter.shouldPassthroughAudio = YES;
? ? //? ? movieFile.playAtActualSpeed = true;
? ? if ([[asset tracksWithMediaType:AVMediaTypeAudio] count] > 0){
? ? ? ? _movieFile.audioEncodingTarget = _movieWriter;
? ? } else {//no audio
? ? ? ? _movieFile.audioEncodingTarget = nil;
? ? }
? ? [_movieFile enableSynchronizedEncodingUsingMovieWriter:_movieWriter];
? ? // 顯示到界面
? ? [_filter addTarget:_movieWriter];
? ? [_movieWriter startRecording];
? ? [_movieFile startProcessing];
?? ?//? ? dlink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateProgress)];
? ? //? ? [dlink setFrameInterval:15];
? ? //? ? [dlink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
? ? //? ? [dlink setPaused:NO];
? ? __weak typeof(self) weakSelf = self;
? ? //渲染
? ? [progressFilter setFrameProcessingCompletionBlock:^(GPUImageOutput *output, CMTime time) {
? ? ? ? //水印可以移動
//? ? ? ? CGRect frame = coverImageView1.frame;
//? ? ? ? frame.origin.x += 1;
//? ? ? ? frame.origin.y += 1;
//? ? ? ? coverImageView1.frame = frame;
? ? ? ? //第5秒之后隱藏coverImageView2
//? ? ? ? if (time.value/time.timescale>=5.0) {
//? ? ? ? ? ? [coverImageView2 removeFromSuperview];
//? ? ? ? }
? ? ? ? [uielement update];
? ? }];
? ? //保存相冊
? ? [_movieWriter setCompletionBlock:^{
? ? ? ? dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//? ? ? ? ? ? __block typeof(self) weakSelf = self;
//? ? ? ? ? ? __strong typeof(self) strongSelf = weakSelf;
? ? ? ? ? ? [weakSelf.filter removeTarget:weakSelf.movieWriter];
? ? ? ? ? ? [weakSelf.movieWriter finishRecording];
? ? ? ? ? ? __block PHObjectPlaceholder *placeholder;
? ? ? ? ? ? if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(pathToMovie))
? ? ? ? ? ? {
? ? ? ? ? ? ? ? NSError *error;
? ? ? ? ? ? ? ? [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
? ? ? ? ? ? ? ? ? ? PHAssetChangeRequest* createAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:movieURL];
? ? ? ? ? ? ? ? ? ? placeholder = [createAssetRequest placeholderForCreatedAsset];
? ? ? ? ? ? ? ? } error:&error];
? ? ? ? ? ? ? ? if (error) {
? ? ? ? ? ? ? ? ? ? [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",error]];
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? else{
? ? ? ? ? ? ? ? ? ? [SVProgressHUD showSuccessWithStatus:@"視頻已經(jīng)保存到相冊"];
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? });
? ? }];
}