iOS: Create image from non-premultiplied [UInt8]

40 views Asked by At

I have a [UInt8] that contains color data in RGBA format. I need to create an image from this data in the most efficient way. Currently, this is what I have:

extension CGImage {
  static func fromData(content: [UInt8], width: Int, height: Int) -> CGImage? {
    guard content.count == width * height * 4,
          let space = CGColorSpace(name: CGColorSpace.sRGB) else {
      return nil
    }
    var content = content
    let context = CGContext(
      data: &content,
      width: width,
      height: height,
      bitsPerComponent: 8,
      bytesPerRow: width * 4,
      space: space,
      bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
    )

    let image = context?.makeImage()
    return image
  }
}

The problem with this is that I must use CGImageAlphaInfo.premultipliedLast (I read somewhere else that iOS only supports premultiplied data) which requires me to do the alpha-multiplication first. I'm using metal to do that, but on big images, it takes around 8ms to do that. Added with other processing time, I ended up with a laggy drawing experience.

Do we have any other way of creating an image from non-premultiplied [UInt8]? It can be CGImage, CIImage, or UIImage.

0

There are 0 answers