有没有一种方法可以在Swift 4中使用CGContext创建没有指针的图像

时间:2018-12-17 06:37:37

标签: ios swift

通过将CGContext与以下代码一起使用,我们可以从缓冲区创建图像。 在这段代码中,您基本上将一个起始地址指向了内存,然后从内存中的该点获取数据以构成一个映像。

但是,如果我们有保存图像数据的变量,那我们说imageData为从其他来源(例如本地网络中的其他设备)下载的数据类型。

        let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer)
        let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer) 
        let colorSpace  = CGColorSpaceCreateDeviceRGB()     
        var bitmapInfo  = CGBitmapInfo.byteOrder32Little.rawValue
        bitmapInfo |= CGImageAlphaInfo.premultipliedFirst.rawValue 
        //CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)

        let context = CGContext(data: baseAddress, width: videoWidth, height: videoHeight, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo)!

        let frameImage =   context.makeImage()!  // This is a CGImage

1 个答案:

答案 0 :(得分:0)

假设您已经有一个名为data的变量,它将图像数据保持为Data类型,那么您可以使用此变量创建图像:

var image = UIImage(data: data)