CGImage from byte array

后端 未结 3 1657
栀梦
栀梦 2020-12-05 02:58

Loading a CGImage or NSImage from a file using a standard image format (jpeg, gif, png et.) is all very simple.

However, I now need to create a CGImage from an arra

3条回答
  •  不知归路
    2020-12-05 03:42

    Old question, but still useful! Swift 4 equivalent of chansuk park's answer:

    let height = 64
    let width = 64
    let numComponents = 3
    let numBytes = height * width * numComponents
    let pixelData = [UInt8](repeating: 210, count: numBytes)
    let colorspace = CGColorSpaceCreateDeviceRGB()
    let rgbData = CFDataCreate(nil, pixelData, numBytes)!
    let provider = CGDataProvider(data: rgbData)!
    let rgbImageRef = CGImage(width: width,
                              height: height,
                              bitsPerComponent: 8,
                              bitsPerPixel: 8 * numComponents,
                              bytesPerRow: width * numComponents,
                              space: colorspace,
                              bitmapInfo: CGBitmapInfo(rawValue: 0),
                              provider: provider,
                              decode: nil,
                              shouldInterpolate: true,
                              intent: CGColorRenderingIntent.defaultIntent)!
    // Do something with rgbImageRef, or for UIImage:
    let outputImage = UIImage(cgImage: rgbImageRef)
    

提交回复
热议问题