Performing Fast Color Space Conversions on iOS and macOS
August 28, 2016
Pixen 3.x defaults to saving artwork in the Generic RGB color space. This is not ideal for a number of reasons. For one, color consistency is not preserved when viewing images on iOS, which uses an sRGB color space system-wide.
In Pixen 4, sRGB will become the default color space for all images. This means that existing artwork will have to be converted from the Generic RGB to sRGB color space.
On macOS, this can be done easily using NSBitmapImageRep. One possible implementation is shown below:
Unfortunately, this code is not cross-platform since NSBitmapImageRep doesn’t exist on iOS, and one of the goals for the new rendering engine in Pixen 4 was iOS support.
Luckily for us, the Accelerate framework provides vImageConvert* functions for performing vectorized color space conversions. In my testing with 2048x2048 image sizes, these are around 45% faster than the NSBitmapImageRep code shown above (averaged over five runs) and they run on both iOS and macOS.
Usage is fairly straightforward, with some comments inline:
Update (August 29, 2016): As Stephen Canon mentioned on Twitter, the vImageConverter should be re-used when doing such conversions multiple times. I tried re-using a single vImageConverter in some code that does color space conversions in tight loops, and it resulted in another ~40% performance improvement.