Reputation: 641
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!!
Upvotes: 4
Views: 1128
Reputation: 438232
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.
Upvotes: 4
Reputation: 66302
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.
Upvotes: 1