jpg or png for UIImage -- which is more efficient? - iphone

I am grabbing an image from the camera roll and then using it for a while as well as save it to disk as a PNG on the iPhone. I am getting the odd crash, presumably due to out of memory.
Does it make a difference if I save it as PNG or JPG (assuming I choose note to degrade the quality in the JPG case)? Specifically:
is more memory then used by the UIImage after I reload it off of disk if I saved it as a PNG?
is it possible the act of saving as PNG uses up more memory transiently during the saving process?
I had been assuming the UIImage was a format neutral representation and it shouldn't matter, but I thought I should verify.

I am getting the odd crash, presumably due to out of memory
Then STOP WHAT YOU ARE DOING RIGHT NOW and first figure out if that's actually the cause of the crash. Otherwise there's a very good chance that you're chasing the wrong problem here, fixing a memory problem that doesn't exist while ignoring the real cause of the crash. If you want to fix a crash, start by figuring out what caused the crash. Following up on what's "presumably" the problem is a recipe for wasted time and effort.

I have an application on the store that needs to save intermediate versions of an image as it's being edited. In the original version, I used PNG format for saving, to avoid quality loss from loading and saving JPEG multiple times.
Sometime around the 2.2 software release, Apple introduced a change into the PNG writing code, such that it takes many times longer to save PNG data from some images. I ended up having to change to saving in JPEG format, because my application was timing out when trying to save images on exit.
Also, you'll run into issues because saving in PNG format doesn't preserve the "orientation" information in the UIImage, so a picture taken in Portrait orientation with the built-in camera will appear rotated after you save and reload it.

It depends on what type of images you're dealing with. If you're dealing with photographic images, JPEGs will almost always be smaller than PNGs, with no discernable loss of detail as can be seen by the human eye.
Conversely, if you're dealing with highly non-photographic images such as GUI elements or images with large blocks of solid colors, then PNGs and JPEGs will be comparable in size, but the PNG will save losslessly whereas the JPEG will be lossy and have very visible artifacts. If you have a really simple image (very large blocks of constant colors, e.g.), then a PNG will very likely be much smaller than a JPEG, and again will not have any compression artifacts.
The act of saving an image as a PNG or JPEG should not take up very much transient memory. When an image is in memory, it is typically stored uncompressed in memory so that it can be drawn to the screen very quickly, as opposed to having to decompress it every time you want to render it. Compared to the size of the uncompressed image, the amount of extra temporary storage you need to compress it is very small. If you can fit the uncompressed image in memory, you don't have to worry about the memory used while compressing it.
And of course, once you write the image to the file system in non-volatile storage and free the in-memory image, it really doesn't matter how big the compressed image is, because it doesn't take up main memory any more. The size of the compressed image only affects how much flash storage it's using, which can be an issue, but it does not affect high likely your app is to run out of memory.

Your crashes may be from a known memory leak in the UIImagePickerController.
This should help you fix that.

I don't have any hard data, but I'd assume that PNGs are preferable because Apple seems to use PNGs virtually everywhere in iPhone OS.
However, if you've already got the code set up for writing PNGs, it shouldn't be too hard to change it to write JPEGs, should it? Just try both methods and see which works better.

Use PNG wherever possible. As part of the compilation XCode runs all PNG files through a utility (pngcrush) to compress and optimize them.

is more memory then used by the UIImage after I reload it off of
disk if I saved it as a PNG?
=> No, it's the same memory size if you import from 2 images that have same resolution and same number of channels. (such as RGBA)
is it possible the act of saving as PNG uses up more memory transiently during the saving process?
=> No, it only effect your disk memory.

Related

What is the fastest way to load compressed images on iOS?

I am writing an iOS app which need to load a lot of full-screen size images into OpenGL. Image storage space is a concern, so I am using png or jpg. Problem is: Loading the image data takes way too long (100s of ms on an iPad2).
I was wondering if someone knows the fastest way to load good-quality compressed image data on an iPad or similar? This could include switching to different image compression formats (?)
Here's what I've found:
Loading jpg via the iOS implementation of libturbo-jpeg is faster than any way I found for png.
If you split jpg images in two, you can parallel-decompress via GCD which almost cuts the load time in half. Still not enough!
The PowerVR compressed PVRTC format can be loaded very quickly, but both compression ratio and image quality are way outside what I need...
No idea how jpeg-2000 would perform, but it seems to be optimized for compression ratio rather than decoding speed.
Any ideas?? This must be a common problem for games or similar..
Are there any newer image formats (jpg is 1986!!) which have portable implementation, maybe slightly less compression than jpg, but decode much faster?
This library might help you out:
https://github.com/path/FastImageCache

Disk cache vs Recreating the image

I currently have an app where I do a lot of image manipulation. I basically take an image that is 320x320 (or 640x640 on Retina) and scale it down to 128x128 (or 256x256 on Retina) before rounding off its corners and applying a glossy highlight. Everything is done using Core Graphics drawing.
At any one time there could be around 600 images that need this processing so I do around 40 on app launch using a background thread and cache them into a FIFO queue. When an image not in the cache needs processing, I do so and add it to the end of the cache, discarding the first cached image. If that first image is needed again it goes through the same process.
What I would like to know is if it would make more sense, and is ultimately more efficient, to save the discarded images to disk rather than recreate them from scratch the next time they are needed, as I could instead just read them from disk.
These images are also displayed using a CALayer and therefore there may be a overhead when the layers' contents are set because of the conversion from UIImage to CGImage. If I store them on disk I believe they can be read directly as a CGImage?
Any ideas and input on improving the efficiency of this process will be sincerely welcomed.
My personal choice would be to use a disk cache.
However, you say 'which is more efficient' - what do you mean?
If you mean faster then the disk cache is probably going to win.
If you mean more space efficient then recreating them will win.
If you mean lower memory usage then it entirely depends on your implementation!
You will have to try it and see :)
However, the advantage of the disk solution is that the second time your app starts up, it will already have done the processing so will start faster. That's why I'd use the disk.
From my experience, saving and then reading from the disk is faster. I had some memory warnings by doing it over and over, instead of saving and reading. But, the only to know for sure is to try. I was using around 1000 images, so it makes senses in my case to use the disk.
It's also good to give a try github's libs that downloads and caches UIImage/NSData from Internet.
It may by SDWebImage(https://github.com/rs/SDWebImage) or APSmartStorage (https://github.com/Alterplay/APSmartStorage).
APSmartStorage helps to get data from network and automatically caches data on disk or in memory in a smart configurable way. Should be good enough.

When to use PNG or JPG in iPhone development?

I have an app that will display a bunch of images in a slideshow. Those images will be part of the bundle, thus distributed with the app.
All the images are photographs or photographic, etc.
I've read that it's preferred to use PNG as the image format, but seeing that the JPG version will be much smaller, I'd rather be using that.
Are there any guidelines which format to use and in which case?
PNG's are pixel perfect (non-lossy), and require very little extra CPU energy to display. However, large PNGs may take longer to read from storage than more compressed image formats, and thus be slower to display.
JPG's are smaller to store, but lossy (amount depends on compression level), and to display them requires a much more complicated decoding algorithm. But the typical compression and image quality is usually quite sufficient for photos.
Use JPG's for photos and for anything large, and PNG's for anything small and/or designed to be displayed "pixel perfect" (e.g. small icons) or as a part of a composited transparent overlay, etc.
Apple optimizes PNG images that are included in your iPhone app bundle. In fact, the iPhone uses a special encoding in which the color bytes are optimized for the hardware. XCode handles this special encoding for you when you build your project. So, you do see additional benefits to using PNG's on an iPhone other than their size consideration. For this reason it is definitely recommended to use PNG's for any images that appear as part of the interface (in a table view, labels, etc).
As for displaying a full screen image such as a photograph you may still reap benefits with PNG's since they are non-lossy and the visual quality should be better than a JPG not to mention resource usage with decoding the image. You may need to decrease the quality of your JPG's in order to see a real benefit in file size but then you are displaying non-optimal images.
File size is certainly a factor but there are other considerations at play as well when choosing an image format.
There is one important thing to think about with PNGs. If a PNG is included in your Xcode build it will be optimized for iOS. This is called PNG crush. If your PNG is downloaded at run time it will not be crushed. Crushed PNGs run about the same as 100% JPGs. Lower quality JPGs run better than higher quality JPGs. So from a performance standpoint from fastest to slowest it would go low quality JPG, high quality JPG, PNG Crushed, PNG.
If you need to download PNGs you should consider crushing the PNGs on the server before the download.
http://www.cocoanetics.com/2011/10/avoiding-image-decompression-sickness/
The Cocoanetics blog published a nice iOS performance benchmark of JPGs at various quality levels, and PNGs, with and without crushing.
From his conclusion:
If you absolutely need an alpha channel or have to go with PNGs then
it is advisable to install the pngcrush tool on your web server and
have it process all your PNGs. In almost all other cases high quality
JPEGs combine smaller file sizes (i.e. faster transmission) with
faster compression and rendering.
It turns out that PNGs are great for small images that you would use
for UI elements, but they are not reasonable to use for any full
screen applications like catalogues or magazines. There you would want
to choose a compression quality between 60 and 80% depending on your
source material.
In terms of getting it all to display you will want to hang onto
UIImage instances from which you have drawn once because those have a
cached uncompressed version of the file in them. And where you don’t
the visual pause for a large image to appear on screen you will have
to force decompression for a couple of images in advance. But bear in
mind that these will take large amounts of RAM and if you are
overdoing it that might cause your app to be terminated. NSCache is a
great place to place frequently used images because this automatically
takes care of evicting the images when RAM becomes scarce.
It is unfortunate that we don’t have any way to know whether or not an
image still needs decompressing or not. Also an image might have
evicted the uncompressed version without informing us as to this
effect. That might be a good Radar to raise at Apple’s bug reporting
site. But fortunately accessing the image as shown above takes no time
if the image is already decompressed. So you could just do that not
only “just in time” but also “just in case”.
Just thought I'd share a bit of decompression performance data...
I'm doing some prototyping of a 360 degree viewer - a carousel where the user can spin through a series of photos taken from different angles, to give the impression of being able to smoothly rotate an object.
I have loaded the image data into an array of NSData's to take file i/o out of the equation, but create NSImage's on the fly. Testing at near max frame rate (~25 fps) and watching in Instruments I see the app is clearly CPU-bound and there's an approximately 10% increase in CPU load showing ~275 kb png's vs. ~75 kb jpg's.
I can't say for sure but my guess is the CPU limit is just from general program execution and moving all the data around in memory, but that image decompression is done on the GPU. Either way and the JPG vs. PNG performance argument looks to favour JPG, especially when the smaller file sizes (and therefore smaller sizes of objects in memory at least in some parts of the chain) is taken into consideration.
Of course every situation is different, there's no substitute for testing...
I have found massive differences in animation performance when using jpegs vs png. For example placing three screen-sized jpegs side by side in a UIScrollView and scrolling horizontally on an iPhone4 results in lag and a thoroughly unpleasant jerky animation. With non-transparent pngs of the same dimensions the scrolling is smooth. I never use jpegs, even if the image is large.
I think if you want to use transparent, you have no choice except PNG. But, if your background is opaque already, then you may use JPG. That is the only difference I can see
'Use JPEG for photos' as mentioned in Human Interface Guidelines under section Produce artwork in the appropriate format.

Converting a normal PNG to iPhone Optimized format

I have an iPhone application that downloads images from the internet and saves them for display later.
The user can select the images to view from a UITableView, the table view has custom cells which display thumbnails of the original images in varying sizes.
When the large image is first downloaded it is scaled to thumbnail size and the thumbnail is saved using UIImagePNGRepresentation.
What I would like to do is save the thumbnail in the optimized iPhone PNG format. How can I do that? does it happen magically just by loading the original large image into memory and saving it? Do I have to do any further processing on the thumbnail before saving?
Chances are the UIImagePNGRepresentation does not create the images, as they are non-comformant PNGs, and can't be read by anything else. If they API generated PNGs that could not be read I think it would document that, and anyone who uploads PNGs from the phone would notice that they did not work.
The optimization is useful, but most of the optimized PNGs are part of the UI where the optimization is done as part of the build process. Chances are the cost of performing the optimization will offset any gains you get from it.
So it turns out that the RGB565 colorspace used in the optimized format is simply not available in a CGGraphicsContext, which is the rendering class used by all the UIwhatever components.
So if I DID write some code to change the color space of the image before saving it, I couldn't get the texture back into a UI class. The only way to use it is to load it directly into the OpenGL innards and use OpenGL in my app.
Don't worry about the "optimized PNG" format, as it isn't making any significant difference.
It does not affect rendering speed at all, and loading speed is dictated by file size more than file format.
So simply save it in a format that will give you smallest files. If you're not using transparency, then it might be JPEG.
If you need transparency, and can spend more CPU time when saving images, then include pngquant in your program (it's under BSD-like license) and shrink those PNGs to 8-bit palette.

Convert .png to PVRTC *on* the iPhone

Is there a standard mechanism or known library that will convert .png images to compressed PVRTC textures on the iPhone itself (not during development using the standard tools on OS X).
I have a number of .png textures in my application but swapping is an issue. I'd like to create PVRTC variants of the .pngs on the device, should the available memory be low on application startup (or perhaps on first load of the application).
I haven't seen any information on the net regarding how to construct PVRTC images manually and to the best of my knowledge there is no support for this built into the iPhone (and it wouldn't be needed to read the PVRTC files).
For most applications, there is little sense to include or construct both versions of the files. Under optimal conditions, the PVRTC versions should be virtually indistinguishable from the PNG versions and are really just "pre-processed" versions of the files optimized for direct streaming into the video memory.
It is generally best to go through all of your images and make decisions regarding how to best package the image to balance memory conservation and quality for all users, not just under specific restricted memory situations.
A few things to consider (apologies if this is redundant knowledge):
PVRTC files can have problems with complex alpha blended images as the pre-processing can cause unsightly artifacts along the blended edges.
Opaque PNG files should have their alpha channel removed in the original image (saving memory and blending overhead).
For images with a limited range of colors, reduce the image from PNG32 to PNG16 or PNG8 to save memory on disk.
If this is for OpenGL based programs, consider using an enhanced version of Texture2D (such as from Cocos2D) which supports alternate pixel formats such as 565 and 4444. This can greatly reduce the overhead in the graphics card with minimal impact on image quality, by carefully choosing a pixel format which corresponds to the balance of colors in the original image.
Additionally for OpenGL based programs, avoid individual images (320x480) for backgrounds as this will result in a 512x512 texture in memory for each one. Break the image into smaller pieces or make the image 512x512 and fill the extra space with other images so that only one texture needs to load.
As with everything, focus on the largest images first to get the biggest bang for the buck.
It's also worth noting that since your application will be the only thing running (other than system applications), the only real memory overhead is going to be a limited amount of "disk" space. Making a second copy of all the image files will actually be working against you instead of helping.
Barney
I'd be careful assuming that this will help you. Once you reference the images once, i.e. load them into a UIImage, the iPhone will start to cache your pngs whether you like them or not. Compressing them will not serve you well to achieve what you're looking for here, in my opinion.
If you want to compress images to PVR on IOS, you may consider the OpenSceneGraph plugin pvr :
http://www.openscenegraph.org/projects/osg/browser/OpenSceneGraph/branches/OpenSceneGraph-3.0/src/osgPlugins/pvr/ReaderWriterPVR.cpp .