iOS 视频图片压缩

作者: 我在鄱阳湖边 | 来源:发表于2017-02-06 17:45 被阅读330次

    #pragma mark - 获取当前时间

    - (NSString*)getCurrentTime{NSDateFormatter*formatter = [[NSDateFormatteralloc] init];

    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];NSString*dateTime = [formatter stringFromDate:[NSDatedate]];//    NSString *str = [NSString stringWithFormat:@"%@mdxx",dateTime];//    NSString *tokenStr = [str stringToMD5:str];returndateTime;

    }

    #pragma mark - 视频压缩/**

    *  视频压缩

    *

    *  @param url 视频文件的url

    *

    *  @return 压缩后的url

    */- (NSURL*)condenseVideoNewUrl: (NSURL*)url{// 沙盒目录NSString*docuPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)[0];NSString*destFilePath = [docuPath stringByAppendingPathComponent:[NSStringstringWithFormat:@"lyh%@.MOV",[selfgetCurrentTime]]];NSURL*destUrl = [NSURLfileURLWithPath:destFilePath];//将视频文件copy到沙盒目录中NSFileManager*manager = [NSFileManagerdefaultManager];NSError*error = nil;

    [manager copyItemAtURL:url toURL:destUrl error:&error];NSLog(@"压缩前--%.2fk",[selfgetFileSize:destFilePath]);// 播放视频/*

    NSURL *videoURL = [NSURL fileURLWithPath:destFilePath];

    AVPlayer *player = [AVPlayer playerWithURL:videoURL];

    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];

    playerLayer.frame = self.view.bounds;

    [self.view.layer addSublayer:playerLayer];

    [player play];

    */// 进行压缩AVAsset*asset = [AVAssetassetWithURL:destUrl];//创建视频资源导出会话/**

    NSString *const AVAssetExportPresetLowQuality; // 低质量

    NSString *const AVAssetExportPresetMediumQuality;

    NSString *const AVAssetExportPresetHighestQuality; //高质量

    */AVAssetExportSession*session = [[AVAssetExportSessionalloc] initWithAsset:asset presetName:AVAssetExportPresetLowQuality];// 创建导出的urlNSString*resultPath = [docuPath stringByAppendingPathComponent:[NSStringstringWithFormat:@"lyhg%@.MOV",[selfgetCurrentTime]]];

    session.outputURL = [NSURLfileURLWithPath:resultPath];// 必须配置输出属性session.outputFileType =@"com.apple.quicktime-movie";// 导出视频[session exportAsynchronouslyWithCompletionHandler:^{NSLog(@"压缩后---%.2fk",[selfgetFileSize:resultPath]);NSLog(@"视频导出完成");

    }];returnsession.outputURL;

    }// 获取视频的大小- (CGFloat) getFileSize:(NSString*)path

    {NSFileManager*fileManager = [[NSFileManageralloc] init] ;floatfilesize =-1.0;if([fileManager fileExistsAtPath:path]) {NSDictionary*fileDic = [fileManager attributesOfItemAtPath:path error:nil];//获取文件的属性unsignedlonglongsize = [[fileDic objectForKey:NSFileSize] longLongValue];

    filesize =1.0*size/1024;

    }returnfilesize;

    }

    #pragma mark - Picker delgate

    - (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {NSString*mediaType = [info objectForKey:UIImagePickerControllerMediaType];if([mediaType isEqualToString:(NSString*)kUTTypeImage]) {NSLog(@"选取的是照片");//        self.imageView.image = info[UIImagePickerControllerEditedImage];// 压缩图片NSData*fileData =UIImageJPEGRepresentation(info[UIImagePickerControllerEditedImage],0.5);//保存到DocumentsNSString*imageStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) lastObject];NSString*imageFile = [imageStr stringByAppendingPathComponent:@"image.jpg"];NSLog(@"%@",imageFile);

    [fileData writeToFile:imageFile atomically:YES];//保存至相册UIImageWriteToSavedPhotosAlbum(info[UIImagePickerControllerEditedImage],self,@selector(image:didFinishSavingWithError:contextInfo:), nil);// 上传图片NSDictionary*dict = @{@"mem_id":@"600209"};

    [AFNetworkTool upLoadToUrlString:@"http://www.baidu.com"parameters:dict fileData:fileData name:@"photo"fileName:@"abc.jpg"mimeType:@"image/jpeg"response:JSON progress:^(NSProgress*uploadProgress) {

    } success:^(NSURLSessionDataTask*task,idresponseObject) {NSLog(@"success:%@ %@",responseObject, [responseObject objectForKey:@"msg"]);

    } failure:^(NSURLSessionDataTask*task,NSError*error) {NSLog(@"%@",error);

    }];

    }else{// 如果是视频NSURL*url = info[UIImagePickerControllerMediaURL];// 获取视频总时长CGFloatlengthTime = [selfgetVideoLength:url];NSLog(@"%f",lengthTime);// 保存视频至相册 (异步线程)NSString*urlStr = [url path];dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{if(UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr)) {UISaveVideoAtPathToSavedPhotosAlbum(urlStr,self,@selector(video:didFinishSavingWithError:contextInfo:), nil);

    }

    });//压缩视频NSData*videoData = [NSDatadataWithContentsOfURL:[selfcondenseVideoNewUrl:url]];//视频上传if(lengthTime >10.0f) {NSLog(@"文件过大只允许上传10s视频");

    }else{NSDictionary*dict = @{@"username":@"syl"};

    [AFNetworkTool upLoadToUrlString:@"http://www.baidu.com"parameters:dict fileData:videoData name:@"file"fileName:@"video.mov"mimeType:@"video/quicktime"response:JSON progress:^(NSProgress*uploadProgress) {

    } success:^(NSURLSessionDataTask*task,idresponseObject) {NSLog(@"上传成功%@",responseObject);

    } failure:^(NSURLSessionDataTask*task,NSError*error) {NSLog(@"%@",error);

    }];

    }

    }

    [selfdismissViewControllerAnimated:YES completion:nil];

    }// 获取视频时间- (CGFloat) getVideoLength:(NSURL*)URL

    {AVURLAsset*avUrl = [AVURLAssetassetWithURL:URL];CMTimetime = [avUrl duration];intsecond = ceil(time.value/time.timescale);returnsecond;

    }

    #pragma mark 图片保存完毕的回调

    - (void) image: (UIImage*) image didFinishSavingWithError:(NSError*) error contextInfo: (void*)contextIn {NSLog(@"照片保存成功");

    }

    #pragma mark 视频保存完毕的回调

    - (void)video:(NSString*)videoPath didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextIn {if(error) {NSLog(@"保存视频过程中发生错误,错误信息:%@",error.localizedDescription);

    }else{NSLog(@"视频保存成功.");

    }

    }

    .h

    typedefNS_ENUM(NSUInteger,ResposeStyle) {JSON,XML,Data,

    };

    typedefNS_ENUM(NSUInteger,RequestStyle) {RequestJSON,RequestString,RequestDefault};

    .m

    @param url 服务器地址

    @param parameters 字典 token

    @param fileData 要上传的数据

    @param name 服务器参数名称 后台给你

    @param fileName 文件名称 图片:xxx.jpg,xxx.png 视频:video.mov

    @param mimeType 文件类型 图片:image/jpg,image/png 视频:video/quicktime

    @param style 返回的数据类型

    @param progress

    @param success

    @param failure

    + (void)upLoadToUrlString:(NSString )urlparameters:(NSDictionary )parametersfileData:(NSData )fileDataname:(NSString )namefileName:(NSString )fileNamemimeType:(NSString )mimeTyperesponse:(ResposeStyle)styleprogress:(void(^)(NSProgress ))progresssuccess:(void(^)(NSURLSessionDataTask , id))successfailure:(void(^)(NSURLSessionDataTask , NSError ))failure {//1.获取单例的网络管理对象AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];//2.根据style 的类型 去选择返回值得类型switch(style) {caseJSON:manager.responseSerializer = [AFJSONResponseSerializer serializer];break;caseXML:manager.responseSerializer = [AFXMLParserResponseSerializer serializer];break;caseData:manager.responseSerializer = [AFHTTPResponseSerializer serializer];break;default:break;

    }//3.设置相应数据支持的类型[manager.responseSerializersetAcceptableContentTypes:[NSSetsetWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"application/json", @"application/x-www-form-urlencoded", nil]];

    [managerPOST:urlparameters:parametersconstructingBodyWithBlock:^(id  _Nonnull formData) {

    [formDataappendPartWithFileData:fileDataname:namefileName:fileNamemimeType:mimeType];

    }progress:^(NSProgress * _Nonnull uploadProgress) {

    }success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {if(success) {

    success(task, responseObject);

    }

    }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {if(failure) {

    failure(task, error);

    }

    }];

    }

    相关文章

      网友评论

        本文标题: iOS 视频图片压缩

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