#pragma mark - 獲取當(dāng)前時(shí)間
- (NSString *)getCurrentTime{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *dateTime = [formatter stringFromDate:[NSDate date]];
//? ? NSString *str = [NSString stringWithFormat:@"%@mdxx",dateTime];
//? ? NSString *tokenStr = [str stringToMD5:str];
return dateTime;
}
#pragma mark - 視頻壓縮
/**
*? 視頻壓縮
*
*? @param url 視頻文件的url
*
*? @return 壓縮后的url
*/
- (NSURL *)condenseVideoNewUrl: (NSURL *)url{
// 沙盒目錄
NSString *docuPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *destFilePath = [docuPath stringByAppendingPathComponent:[NSString stringWithFormat:@"lyh%@.MOV",[self getCurrentTime]]];
NSURL *destUrl = [NSURL fileURLWithPath:destFilePath];
//將視頻文件copy到沙盒目錄中
NSFileManager *manager = [NSFileManager defaultManager];
NSError *error = nil;
[manager copyItemAtURL:url toURL:destUrl error:&error];
NSLog(@"壓縮前--%.2fk",[self getFileSize: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 = [AVAsset assetWithURL:destUrl];
//創(chuàng)建視頻資源導(dǎo)出會(huì)話
/**
NSString *const AVAssetExportPresetLowQuality; // 低質(zhì)量
NSString *const AVAssetExportPresetMediumQuality;
NSString *const AVAssetExportPresetHighestQuality; //高質(zhì)量
*/
AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetLowQuality];
// 創(chuàng)建導(dǎo)出的url
NSString *resultPath = [docuPath stringByAppendingPathComponent:[NSString stringWithFormat:@"lyhg%@.MOV",[self getCurrentTime]]];
session.outputURL = [NSURL fileURLWithPath:resultPath];
// 必須配置輸出屬性
session.outputFileType = @"com.apple.quicktime-movie";
// 導(dǎo)出視頻
[session exportAsynchronouslyWithCompletionHandler:^{
NSLog(@"壓縮后---%.2fk",[self getFileSize:resultPath]);
NSLog(@"視頻導(dǎo)出完成");
}];
return session.outputURL;
}
// 獲取視頻的大小
- (CGFloat) getFileSize:(NSString *)path
{
NSFileManager *fileManager = [[NSFileManager alloc] init] ;
float filesize = -1.0;
if ([fileManager fileExistsAtPath:path]) {
NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];//獲取文件的屬性
unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
filesize = 1.0*size/1024;
}
return filesize;
}
#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);
//保存到Documents
NSString *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, id responseObject) {
NSLog(@"success:%@ %@",responseObject, [responseObject objectForKey:@"msg"]);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"%@",error);
}];
}else{
// 如果是視頻
NSURL *url = info[UIImagePickerControllerMediaURL];
// 獲取視頻總時(shí)長(zhǎng)
CGFloat lengthTime = [self getVideoLength: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 = [NSData dataWithContentsOfURL:[self condenseVideoNewUrl: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, id responseObject) {
NSLog(@"上傳成功%@",responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"%@",error);
}];
}
}
[self dismissViewControllerAnimated:YES completion:nil];
}
// 獲取視頻時(shí)間
- (CGFloat) getVideoLength:(NSURL *)URL
{
AVURLAsset *avUrl = [AVURLAsset assetWithURL:URL];
CMTime time = [avUrl duration];
int second = ceil(time.value/time.timescale);
return second;
}
#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(@"保存視頻過程中發(fā)生錯(cuò)誤,錯(cuò)誤信息:%@",error.localizedDescription);
}else{
NSLog(@"視頻保存成功.");
}
}