Mackie D Mackie D - 1 month ago 22
iOS Question

How to convert PNG image to CMYK in iOS?

I have a set of user-generated PNG images that I need to embed into print-ready PDFs. One of the constraints set by the printing company is that all images be in the CMYK colorspace. How do I convert a PNG (or UIImage containing that PNG) to CMYK? By default the colorspace is sRGB.

Answer

You should consider CGColorSpace class and CGColorSpaceCreateDeviceCMYK function. You can create a CGContex using this initializer and pass CMYK color space as a parameter to it. Then just draw a CGImage from that context and create UIImage from it.

Example:

func createCMYK(fromRGB image: UIImage) -> UIImage? {
    let size = image.size
    let colorSpace:CGColorSpace = CGColorSpaceCreateDeviceCMYK()
    let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
    guard let context = CGContext(data: nil,
                                  width: Int(size.width),
                                  height: Int(size.height),
                                  bitsPerComponent: 8,
                                  bytesPerRow: 4 * Int(size.width),
                                  space: colorSpace,
                                  bitmapInfo: bitmapInfo.rawValue) else { return nil }            
    context.draw(image.cgImage!, in: CGRect(origin: .zero, size: size))
    guard let cgImage = context.makeImage() else { return nil }
    return UIImage(cgImage: cgImage)
}