iOS 視頻圖片壓縮上傳

#pragma mark - 獲取當(dāng)前時(shí)間

- (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];

*/// 進(jìn)行壓縮AVAsset*asset = [AVAssetassetWithURL:destUrl];//創(chuàng)建視頻資源導(dǎo)出會(huì)話/**

NSString *const AVAssetExportPresetLowQuality; // 低質(zhì)量

NSString *const AVAssetExportPresetMediumQuality;

NSString *const AVAssetExportPresetHighestQuality; //高質(zhì)量

*/AVAssetExportSession*session = [[AVAssetExportSessionalloc] initWithAsset:asset presetName:AVAssetExportPresetLowQuality];// 創(chuàng)建導(dǎo)出的urlNSString*resultPath = [docuPath stringByAppendingPathComponent:[NSStringstringWithFormat:@"lyhg%@.MOV",[selfgetCurrentTime]]];

session.outputURL = [NSURLfileURLWithPath:resultPath];// 必須配置輸出屬性session.outputFileType =@"com.apple.quicktime-movie";// 導(dǎo)出視頻[session exportAsynchronouslyWithCompletionHandler:^{NSLog(@"壓縮后---%.2fk",[selfgetFileSize:resultPath]);NSLog(@"視頻導(dǎo)出完成");

}];returnsession.outputURL;

}// 獲取視頻的大小- (CGFloat) getFileSize:(NSString*)path

{NSFileManager*fileManager = [[NSFileManageralloc] init] ;floatfilesize =-1.0;if([fileManager fileExistsAtPath:path]) {NSDictionary*fileDic = [fileManager attributesOfItemAtPath:path error:nil];//獲取文件的屬性u(píng)nsignedlonglongsize = [[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];//保存至相冊(cè)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];// 獲取視頻總時(shí)長(zhǎng)CGFloatlengthTime = [selfgetVideoLength:url];NSLog(@"%f",lengthTime);// 保存視頻至相冊(cè) (異步線程)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(@"文件過(guò)大只允許上傳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];

}// 獲取視頻時(shí)間- (CGFloat) getVideoLength:(NSURL*)URL

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

}

#pragma mark 圖片保存完畢的回調(diào)

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

}

#pragma mark 視頻保存完畢的回調(diào)

- (void)video:(NSString*)videoPath didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextIn {if(error) {NSLog(@"保存視頻過(guò)程中發(fā)生錯(cuò)誤,錯(cuò)誤信息:%@",error.localizedDescription);

}else{NSLog(@"視頻保存成功.");

}

}

.h

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

};

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

.m

@param url 服務(wù)器地址

@param parameters 字典 token

@param fileData 要上傳的數(shù)據(jù)

@param name 服務(wù)器參數(shù)名稱(chēng) 后臺(tái)給你

@param fileName 文件名稱(chēng) 圖片:xxx.jpg,xxx.png 視頻:video.mov

@param mimeType 文件類(lèi)型 圖片:image/jpg,image/png 視頻:video/quicktime

@param style 返回的數(shù)據(jù)類(lèi)型

@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.獲取單例的網(wǎng)絡(luò)管理對(duì)象AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];//2.根據(jù)style 的類(lèi)型 去選擇返回值得類(lèi)型switch(style) {caseJSON:manager.responseSerializer = [AFJSONResponseSerializer serializer];break;caseXML:manager.responseSerializer = [AFXMLParserResponseSerializer serializer];break;caseData:manager.responseSerializer = [AFHTTPResponseSerializer serializer];break;default:break;

}//3.設(shè)置相應(yīng)數(shù)據(jù)支持的類(lèi)型[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);

}

}];

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容