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?
Asked
Active
Viewed 208 times
3
-
possible duplicate of [get size of a uiimage (bytes length) not height and width](http://stackoverflow.com/questions/1296707/get-size-of-a-uiimage-bytes-length-not-height-and-width) – Joe Feb 24 '12 at 18:00
2 Answers
1
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
.

Mike Weller
- 45,401
- 15
- 131
- 151
-
This gives you the size of the image's bitmap, but the UIImage doesn't necessarily always store the bitmap in memory! If the image is backed by a file, then CG and/or UIKit are free to create the bitmap on-demand by decoding the file. So, this method is maybe useful as a rough guideline, but it may not be 100% accurate. – Kurt Revis May 03 '12 at 15:56
-
This is true. I assume he wants to know the memory use once the image has been loaded. – Mike Weller May 04 '12 at 10:51
-1
What Joe said, this will give you the number of bytes for the image, unless "the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format."
NSData *imageData = UIImagePNGRepresentation(image)
if (imageData)
{
NSUInteger numBytes = [imageData bytes];
}
-
Images in memory are stored uncompressed. Getting the number of bytes from the PNG compressed image is not useful in this case. – Mike Weller May 03 '12 at 15:05