Creating A CGImage From Color Array


(Brandon O'Dell) #1


I created an Android app that is not yet released. I am porting it over to iOS and have just about everything complete except for one thing.

I am saving user icons (8px by 8px) to a database as an array of Int colors. On the Android version I am creating a bitmap image from the array and assigning that as the user icon.

However, on the iOS I am unable to find a way to convert the array to an image format that I can load into a UIImageView. If there is a better way of doing this or you have a solution it would be greatly appreciated if you share your information with me and other who may be in the same boat as me.

If you need any more information I will be happy to provide it.

(Jens Persson) #2

What do you mean by "Int colors"? You have to know exactly what pixel format you want, and then you can do something like the following (which assumes each element in the array is a 32 bit uint containing b g r a bytes sRGB):

    var srgbArray = [UInt32](repeating: 0xFF204080, count: 8*8)
    let cgImg = srgbArray.withUnsafeMutableBytes { (ptr) -> CGImage in
        let ctx = CGContext(
            data: ptr.baseAddress,
            width: 8,
            height: 8,
            bitsPerComponent: 8,
            bytesPerRow: 4*8,
            space: CGColorSpace(name: CGColorSpace.sRGB)!,
            bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue +
        return ctx.makeImage()!


I’ve been in this situation before, and Jens is right, you have to go through the low-level CGContext stuff. For as much as Apple is lauded for the quality of its color-handling stack, I really think this ought to fall under “simple things should be simple”.

I have the pixel data, I want to turn it to an image exactly as-is, without any modification to the data. In other languages this is almost trivial. For example, Matlab lets you call imwrite(array, filepath) to create a new image file. There are lots of other options available if you want them, but for the simple case of “create an image with exactly these value for its pixels”, there’s doesn’t have to be any extra complexity.

Unfortunately, to the best of my knowledge Apple does not provide a similar simple solution.

(Brandon O'Dell) #4

Thank you so much for the reply! It worked perfectly.

They are called Int colors on Android, basically they are integers from -1 to -16777216 that correspond with a certain RGB color.