iOS - 获取从照片卷轴中选择的图像的文件大小

时间:2014-12-02 08:16:23

标签: ios objective-c

我正在构建一个应用程序,允许用户从他们的设备中选择照片和视频并将其上传到服务器。试图获取每个项目的文件大小(以字节为单位),任何人都可以帮助我吗?

if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto){ // image file
        if ([dict objectForKey:UIImagePickerControllerOriginalImage]){
            NSURL* urlPath=[dict objectForKey:@"UIImagePickerControllerReferenceURL"];

            item = [BundleItem itemWithPath:urlPath AndDescription:nil];
            item.itemImage = [dict objectForKeyedSubscript:UIImagePickerControllerOriginalImage];
            item.itemType = 1; // image
            item.itemSize = // what do I need here??
            [m_items addObject:item];
        }
    } else if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypeVideo){ // video file
        if ([dict objectForKey:UIImagePickerControllerOriginalImage]){
            NSURL* urlPath=[dict objectForKey:@"UIImagePickerControllerReferenceURL"];
            item = [BundleItem itemWithPath:urlPath AndDescription:nil];
            item.itemImage = [dict objectForKeyedSubscript:UIImagePickerControllerOriginalImage];
            item.itemType = 2; // video
            item.itemSize = // what do I need here??
            [m_items addObject:item];
        }
    }

修改

使用视频获取NSCocaoErrorDomain 256:

            NSURL* urlPath=[dict objectForKey:@"UIImagePickerControllerReferenceURL"];

            item = [BundleItem itemWithPath:urlPath AndDescription:nil];
            item.itemImage = [dict objectForKeyedSubscript:UIImagePickerControllerOriginalImage];
            item.itemType = 2; // video

            //Error Container
            NSError *attributesError;
            NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[urlPath path] error:&attributesError];
            NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
            long fileSize = [fileSizeNumber longValue];
            item.itemSize = fileSize;

            [m_items addObject:item];

1 个答案:

答案 0 :(得分:2)

仅适用于图片数据选择:

item.itemImage = (UIImage*)[info valueForKey:UIImagePickerControllerOriginalImage];
NSData *imgData = UIImageJPEGRepresentation(item.itemImage, 1); //1 it represents the quality of the image.
NSLog(@"Size of Image(bytes):%d",[imgData length]);

希望这会对你有所帮助。

以下方法概括,它适用于图像和视频:

这样的事情应该注意查找从 UIImagePickerController

返回的所选图像或视频的文件大小
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{

        NSURL *videoUrl=(NSURL*)[info objectForKey:UIImagePickerControllerMediaURL];

        //Error Container
        NSError *attributesError;
        NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[videoUrl path] error:&attributesError];
        NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
        long long fileSize = [fileSizeNumber longLongValue];
}