关闭

iOS 视频图片压缩上传

420人阅读 评论(0) 收藏 举报

iOS 视频图片压缩上传

字数829 阅读758 评论2 

视频上传方法:http://www.jianshu.com/p/a89b1821162a

#pragma mark - 获取当前时间
- (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];
    */
    // 进行压缩
    AVAsset *asset = [AVAsset assetWithURL:destUrl];
    //创建视频资源导出会话
    /**
     NSString *const AVAssetExportPresetLowQuality; // 低质量
     NSString *const AVAssetExportPresetMediumQuality;
     NSString *const AVAssetExportPresetHighestQuality; //高质量
     */

    AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetLowQuality];
    // 创建导出的url
    NSString *resultPath = [docuPath stringByAppendingPathComponent:[NSString stringWithFormat:@"lyhg%@.MOV",[self getCurrentTime]]];
    session.outputURL = [NSURL fileURLWithPath:resultPath];
    // 必须配置输出属性
    session.outputFileType = @"com.apple.quicktime-movie";
    // 导出视频
    [session exportAsynchronouslyWithCompletionHandler:^{
        NSLog(@"压缩后---%.2fk",[self getFileSize:resultPath]);
        NSLog(@"视频导出完成");

    }];

    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<NSString *,id> *)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];

        //保存至相册
        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];
       // 获取视频总时长
        CGFloat lengthTime = [self getVideoLength: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 = [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];
}
// 获取视频时间
- (CGFloat) getVideoLength:(NSURL *)URL
{
    AVURLAsset *avUrl = [AVURLAsset assetWithURL:URL];
    CMTime time = [avUrl duration];
    int second = ceil(time.value/time.timescale);
    return second;
}
#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(@"视频保存成功.");
    }
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:31682次
    • 积分:934
    • 等级:
    • 排名:千里之外
    • 原创:60篇
    • 转载:30篇
    • 译文:0篇
    • 评论:1条
    最新评论