I have several .png
images (ETA: but the format could also be JPEG or something else) that I am going to display in UITableViewCell
s. Right now, in order to get the row heights, I load in the images, get their size
properties, and use that to figure out how high to make the rows (calculating any necessary changes along the way, since most of the images get resized before being displayed). In order to speed things up and reduce memory usage, I'd like to be able to get size
without loading the images. Is there a way to do this?
Note: I know that there are a number of shortcuts I could implement to eliminate this issue, but for several reasons I can't resize images in advance or collect the image sizes in advance, forcing me to get this info at run time.
imageUrl is an NSURL, also import ImageIO/ImageIO.h with <> around it.
As of iOS SDK 4.0, this task can be accomplished with the ImageIO framework (
CGImageSource...
). I have answered a similar question here.It should be pretty simple. PNG spec has an explanation of a PNG datastream (which is effectively a file). IHDR section contains information about image dimensions.
So what you have to do is to read in
PNG
"magic value" and then read two four-byte integers, which will be width and height, respectively. You might also need to reorder bits in these values (not sure how are they stored), but once you figure that out, it will be very simple.Try using the CGImageCreateWithPNGDataProvider and CGImageCreateWithJPEGDataProvider functions. I don't know whether they're lazy enough or not, or whether that's even possible for JPEG, but it's worth trying.
//Here's a quick & dirty port to C#
}
This is nicely implemented in Perl's Image::Size module for about a dozen formats -- including PNG and JPEG. In order to re-implement it in Objective C just take the perl code and read it as pseudocode ;-)
For instance, pngsize() is defined as
jpegsize is only a few lines longer.