Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the amount of RAM a particular UIImage uses?

Tags:

objective-c

I'm curious as to whether there is a public or private API to let me learn how much RAM any given UIImage uses? Anybody know how to get its size reliably?


1 Answers

A UIImage's data will be stored as decompressed data in memory, so you can ignore the suggestions of checking the byte length of UIImagePNGRepresentation etc.

The easiest solution is to grab the CGImageRef and use this code:

- (size_t)byteSizeForImage:(UIImage *)image {
    CGImageRef imageRef = image.CGImage;

    size_t bitsPerPixel = CGImageGetBitsPerPixel(imageRef);
    size_t bitsTotal =  CGImageGetWidth(imageRef) * CGImageGetHeight(imageRef) *
                            bitsPerPixel;
    size_t bytesTotal = bitsTotal / 8;
    return bytesTotal;
}

Most of the time your images will be RGB (3 bytes per pixel) or RGBA (4 bytes per pixel) so this usually works out to be width * height * 3 or width * height * 4.

like image 175
Mike Weller Avatar answered Jan 25 '26 14:01

Mike Weller