William Falcon William Falcon - 5 months ago 285
iOS Question

Determine image MB size from PHAsset

I want to determine the memory size of the image accessed through the PHAsset. This size is so that we know how much memory it occupies on the device. Which method does this?

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)")


Results in:

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


Which one of these values actually represents the amount it occupies on the device?

Answer

After emailing the picture to myself and checking the size on the system, it turns out approach ONE is the closest to the actual size.

To get the size of a PHAsset (Image type), I used the following method:

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)
 }

Command + I on my macbook shows the image size as 1,575,062 bytes.
imageSize in my program shows the size at 1,576,960 bytes.
I tested with five other images and the two sizes reported were just as close.