从PHAsset确定图像MB大小

时间:2014-08-20 02:37:43

标签: ios swift

我想确定通过PHAsset访问的图像的内存大小。这个大小使我们知道它在设备上占用了多少内存。这是哪种方法?

var imageSize = Float(imageData.length)


        var image = UIImage(data: imageData)
        var jpegSize = UIImageJPEGRepresentation(image, 1)
        var pngSize = UIImagePNGRepresentation(image)
        var pixelsMultiplied = asset.pixelHeight * asset.pixelWidth

        println("regular data: \(imageSize)\nJPEG Size: \(jpegSize.length)\nPNG Size: \(pngSize.length)\nPixel multiplied: \(pixelsMultiplied)")

结果:

regular data: 1576960.0
JPEG Size: 4604156
PNG Size: 14005689
Pixel multiplied: 7990272

这些值中的哪一个实际上代表了它在设备上占用的数量?

2 个答案:

答案 0 :(得分:7)

将图片通过电子邮件发送给自己并检查系统尺寸后,结果显示接近ONE 最接近实际尺寸。

为了获得PHAsset(图像类型)的大小,我使用了以下方法:

var asset = self.fetchResults[index] as PHAsset

self.imageManager.requestImageDataForAsset(asset, options: nil) { (data:NSData!, string:String!, orientation:UIImageOrientation, object:[NSObject : AnyObject]!) -> Void in
    //transform into image
    var image = UIImage(data: data)

    //Get bytes size of image
    var imageSize = Float(data.length)

    //Transform into Megabytes
    imageSize = imageSize/(1024*1024)
 }

我的macbook上的Command + I将图像大小显示为 1,575,062 字节 我的程序中的imageSize显示 1,576,960 字节的大小 我测试了其他五个图像,报告的两个尺寸也很接近。

答案 1 :(得分:4)

当数据过大时,NSData方法变得不稳定。您可以使用以下作为替代方案:

[[PHImageManager defaultManager] requestAVAssetForVideo:self.phAsset options:nil resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {

    CGFloat rawSize = 0;

    if ([asset isKindOfClass:[AVURLAsset class]])
    {
        AVURLAsset *URLAsset = (AVURLAsset *)asset;
        NSNumber *size;
        [URLAsset.URL getResourceValue:&size forKey:NSURLFileSizeKey error:nil];
        rawSize = [size floatValue] / (1024.0 * 1024.0);
    }
    else if ([asset isKindOfClass:[AVComposition class]])
    {
        // Asset is an AVComposition (e.g. slomo video)

        float estimatedSize = 0.0;

        NSArray *tracks = [self tracks];
        for (AVAssetTrack * track in tracks)
        {
            float rate = [track estimatedDataRate] / 8.0f; // convert bits per second to bytes per second
            float seconds = CMTimeGetSeconds([track timeRange].duration);
            estimatedSize += seconds * rate;
        }

        rawSize = estimatedSize;
    }

    if (completionBlock)
    {
        NSError *error = info[PHImageErrorKey];
        completionBlock(rawSize, error);
    }

}];

对于ALAssets,如下所示:

        [[[ALAssetsLibrary alloc] init] assetForURL:asset.URL resultBlock:^(ALAsset *asset) {

            long long sizeBytes = [[asset defaultRepresentation] size];

            if (completionBlock)
            {
                completionBlock(sizeBytes, nil);
            }

        } failureBlock:^(NSError *error) {

            if (completionBlock)
            {
                completionBlock(0, error);
            }

        }];