How to determine the number of bytes used by a UIImage? - ios

I would like to be able to calculate the total number of bytes a UIImage uses in memory.
I can make a rough estimate by multiplying the width by the height and then by a multiplier number of bytes, but I'd like to calculate the size exactly if possible.

In general, objects don't have a single meaningful "size", since they can allocate and release any number of other objects privately as needed. sizeof(*myObj) only gives you the size of the top level structure, not a very useful number. If you need the complete memory impact of allocating and using an object, run under Instruments and watch allocations.
For a UIImage, its practical size is the size of whatever is backing it, typically either an NSData containing a PNG, or a CGimageRef, plus the object overhead. (There's also the pixel buffer when it gets rendered to the screen or other context; but that buffer belongs to the view or context in question, not the UIImage. If a UIView is doing the rendering then that buffer is likely in GL texture memory anyway.)
[UIImage imageWithData:[NSData dataWithContentsOfFile:#"foo.png"]] gives you a UIImage that is the same size as the foo.png file, plus some inconsequential overhead. [UIImage imageNamed:#"foo.png"] does the same thing, except that the class maintains a cache table of one object per filename, and will cause that object to dump its memory copy of the png in low-memory situations, reducing its "size" to just the overhead.
imageWithCGImage: and variants give you an UIImage that uses a CGImage reference as its backing store, and CGImages can be any number of things depending on their source. If you've been painting in one, it's probably an uncompressed pixel buffer. Calculate its size exactly as you propose above. If you need what its size "would be" if it were from a file, inspect the result of the UIImagePNGRepresentation or UIImageJPEGRepresentation functions.

Width * height * 4 will get you close. I'm not sure there's a way to get the exact size, since width is rounded out to an arbitrary, undocumented boundary (at least 4 pixels or 16 bytes, I gather), and there are several extra internal pieces of the object that you'd need to count. Plus likely there are internal attributes that are hung on the object or not, based on its use.

I had to solve this for a twitter app I was writing. Twitter rejects images larger than 3MB, so I needed to compress the image just enough to get below the 3MB limit. Here is the code snippet I used:
float compression = 1.0f;
NSData* data = UIImageJPEGRepresentation(photo, compression);
while(data.length > 3145728) //3MB
{
compression -= .1f;
NSLog(#"Compressing Image to: %lf", compression);
data = UIImageJPEGRepresentation(photo, compression);
NSLog(#"Image Bytes: %i", data.length);
}
The compression algorithm I used is non-optimized.
So, What is it doing?
Good question! The UIImageJPEGRepresentation method returns a byte array. To get the size, simply check the length of the array!
There is also a UIImagePNGRepresentation method. Keep in mind, these method are having to build byte arrays, and if needed convert the binary representation of the data. This can take a bit of time. Luckily in my case, most images taken by the iPhone are already less than 3MB, and will only need the compression if there is a wide range of colors; but calling the UIImageJPEGRepresentation method repeatedly (which could happen in my posted code) can take some time.

Related

How to optimize the memory when displaying same image multiple times?

I have an instance of UIImage with an image with size of 200KB, then I create 5 instances of UIImageView that reference to same this UIImage.
I wonder how much memory allocated in this case - only 200KB (of one UIImage instance) or 1MB (for 5 cloned UIImage instances)? In the case of wasting memory occured, is there effective way to solve it?
A couple of thoughts:
UIImage is a reference type, so when you reference the same image five times, you generally will have one image object in memory. It depends a little upon how you do this. For example, if you use UIImage(data:) each time, or something like that, it's possible to instantiate a new object each time, but if you instantiate only one UIImage and then proceed to use if five times, then you won't see duplicative memory consumption taking place.
As an aside:
You say the image has a size of 200kb. Is that the size of the original asset, or have you figured out that this is how much memory it will take at run time?
The reason I ask is that JPG and PNG files are generally compressed, but when you use it in an image view, it will be uncompressed. The amount of memory that an image takes has little to do with the file size of the original asset, but rather corresponds to the dimensions (in pixels) of the image. So a random PNG that is 676 kb that is 2560 x 1440 pixels may actually require 14mb of memory (four bytes per pixel).
Note, this memory consumption corresponds to the dimension of the image in question, not the dimensions of the image view to which you added it. If you're concerned about memory usage and if the image dimensions exceed the size of the image view (times the device scale), then you might want to consider resizing the image.
In the future, you can answer these questions empirically using Instruments. For example, in the following timeline, at the green signpost, I loaded a UIImage with the 676kb asset with modest memory impact, I set the image view image to use this asset at the purple signpost with a significant memory impact as it uncompressed this 2560 x 1440 px image, and I loaded five more image views with the same image at the orange signpost with negligible further memory impact.

iphone sdk get actual size of image in bytes

How to get actual size of image ?
I am using
NSInteger actualSize = CGImageGetHeight(image.CGImage) * CGImageGetBytesPerRow(image.CGImage);
or
NSData *imageData2 = UIImageJPEGRepresentation(image, 1.0);
[imageData2 length];
but I don't get the actual size of image it is either larger of smaller compared to the size on the disk (as I am using simulator).
Is there any way to get actual size of the image?
It depends upon what you mean by "size".
If you want the amount of memory used while the image is loaded into memory and used by the app, the bytes-per-row times height is the way to go. This captures the amount of memory used by the uncompressed pixel buffer while the image is actively used by the app.
If you want the number of bytes used in persistent storage when you save the image (generally enjoying some compression), then grab the the original asset's NSData and examine its length. Note, though, if you load an image and then use UIImageJPEGRepresentation with a quality of 1, you'll generally get a size a good deal larger than the original compressed file.
Bottom line, standard JPEG and PNG files enjoy some compression, but when the image is loaded into memory it is uncompressed. You can't generally infer the original file size from a UIImage object. You have to look at the original asset.
Try this (for iOS 6.0 or later and OS X 10.8):
NSLog(#"%#",[NSByteCountFormatter stringFromByteCount:imageData2.length countStyle:NSByteCountFormatterCountStyleFile]);
UPDATE:
Question: Can you post code where you initialise your image?
Above solution did not work for you. Let's try something else. You could try to check directly image file size:
NSError* error;
NSDictionary *fileDictionary = [[NSFileManager defaultManager] attributesOfItemAtPath:mediaURL error: &error];
NSNumber *size = [fileDictionary objectForKey:NSFileSize];

How can I find out how much memory a UIImageView is using?

I'm making an app that uses a large amount of UIImageView's and I am wanting to find out the size of each of the UIImageViews's to try and take a look at the app's memory usage in more detail.
I have played around with Instruments and I can see the amount of memory being alloced by the app but I am wanting a more in depth look at what objects use what memory. For example something like:
UIImageViewOne 10Mb
UIImageViewTwo 8Mb
UIImageViewThree 9Mb
UIImageViewFour 3Mb
Is this possible with Instruments or is there an easier way to view this information?
If you want to determine the amount of memory that will be used by an image, you can look at the cgImage property (which returns a CGImageRef) and then supply that as the parameter to bytesPerRow and multiply that by the height of the image. So, would look like the following (in Objective-C implementation would use CGImageGetBytesPerRow and CGImageGetHeight):
guard let cgImage = image.cgImage else { return }
let bytes = cgImage.bytesPerRow * cgImage.height
This, calculates the size of the pixel buffer used by the image when it is uncompressed and used within the app. Frequently this total is equal to 4 times the width times the height (both measured in pixels). (This is one byte for each of the four channels, red, green, blue, and alpha.) This isn't all of the memory associated with the image, but it accounts for the vast majority of it.
When I ran the above code on my 2,880 × 1,800 pixel image, it reported that it took 20,736,000 bytes (i.e. 19.78 mb).
As you know, if you want to see this in instruments, you can use the allocations tool and then drag within a specific range in the graph and you'll see the objects allocated, but not released, within that time period:
You'll see that for that selected range, the largest allocation was 19.78 mb of a ImageIO_PNG_Data (or if you used a JPG, you'd see a ImageIO_jpeg_Data).
Unfortunately, tracking these ImageIO allocations back to our code is a little more complicated than with most memory allocations, because of the sleight of hand that iOS does during the uncompression. But you can see how this ImageIO allocation correlates to the calculated pixel buffer size.
(See revision history for rendition for earlier versions of Swift.)

UIImage takes up much more memory than its NSData

I'm loading a UIImage from NSData with the following code
var image = UIImage(data: data!)
However, there is a weird behavior.
At first, I used png data, and the NSData was about 80kB each.
When I set UIImage with the data, the UIImage took up 128kb each.
(Checked with Allocation instrument, the size of ImageIO_PNG_Data)
Then I changed to use jpeg instead, and the NSData became about 7kb each.
But still, the UIImage is 128kb each, so when displaying the image I get no memory advantage! (The NSData reduced to 80kb -> 7kb and still the UIImage takes up the same amount of memory)
It is weird, why the UIImage should take up 128kb when the original data is just 7kb?
Can I reduce this memory usage by UIImage without shrinking the size of the UIImage itself??
Note that I'm not dealing with high resolution image so resizing the image is not an option (The NSData is already 7kb!!)
Any help will be appreciated.
Thanks!!
When you access the NSData, it is often compressed (with either PNG or JPEG). When you use the UIImage, there is an uncompressed pixel buffer which is often 4 bytes per pixel (one byte for red, green, blue, and alpha, respectively). There are other formats, but it illustrates the basic idea, that the JPEG or PNG representations can be compressed, when you start using an image, it is uncompressed.
In your conclusion, you say that resizing not an option and that the NSData is already 7kb. I would suggest that resizing should be considered if the resolution of the image is greater than the resolution (the points of the bounds/frame times the scale of the device) of the UIImageView in which you're using it. The question of whether to resize is not a function of the size of the NSData, but rather the resolution of the view. So, if you have a 1000x1000 pixel image that you're using in a small thumbview in a table view, then regardless of how small the JPEG representation is, you should definitely resize the image.
This is normal. When the image is stored as NSData, it is compressed (usually using PNG or JPG compression). When it's a UIImage, the image is decompressed, which allows it to be drawn quickly on the screen.

Poor memory management performance for images on ios devices

I have the following issue:
I have a primary view object (that inherits from UIView) that displays a grid of 16 squares (each is a class I created that inherits from UIImageView), in a 4x4 layout.
Each of these 16 squares is 160x160, and contains an image (a different image for each square) that is no bigger than 30kb. The image, however, is 500x500 (because it is used elsewhere in the program, in its full size), so it gets resized in the "square" class to 160x160, by the setFrame method.
By looking at the memory management feature of Xcode when the app is running, I've noticed a few things:
each of these squares, when added to the primary view object, increase the memory usage of the app by 1MB. This doesn't happen at instantiation, but only when they are added by [self addSubview:square] at the primary view object.
if I use the same image for all the squares, the memory increase is
minimal. If I initialize the square objects without any images, then
the increase is basically zero.
the same app, when running in the simulator, uses 1/6 of the memory
it does on an actual device.
The whole point here is: why is each of the squares using up 1MB of memory when loading a 30kb image? Is there a way to reduce this? I've tried creating the images in a number of different ways: [UIImage imageNamed:img], [UIImage imageWithContentsFromFile:path], [UIImage imageWithData:imgData scale:scale], as well as not resizing the frame.
When you use a 500x500 image in a smaller UIImageView, it's still loading the larger image into memory. You can solve this by resizing the UIImage, itself (not just adjusting the frame of the UIImageView), making a 160x160 image, and use that image in your view. See this answer for some code to resize the image, which can then be invoked as follows:
UIImage *smallImage = [image scaleImageToSizeAspectFill:CGSizeMake(160, 160)];
You might even want to save the resized image, so you're not constantly encumbering yourself with the computational overhead of creating the smaller images every time, e.g.:
NSData *data = UIImagePNGRepresentation(smallImage);
[data writeToFile:path atomically:YES];
You can then load that PNG file corresponding to your small image in future invocations of the view.
In answer to your question why it takes up so much memory, it's because while the image is probably stored as a compressed JPG or PNG in persistent storage, I suspect in memory it's held as an uncompressed bitmap. There are many internal formats, but a common one is a 32-bit format with 8 bits each for red, green, blue, and alpha. Regardless of the specifics, you can quickly see how a 500 x 500 pixel representation, with 4 bytes per pixel could translate to a 1 mb of memory. But a 160 x 160 image should be roughly one tenth the size.

Resources