Pixel Array to UIImage in Swift

前端 未结 2 1351
长情又很酷
长情又很酷 2020-11-30 08:12

I\'ve been trying to figure out how to convert an array of rgb pixel data to a UIImage in Swift.

I\'m keeping the rgb data per pixel in a simple struct:

<         


        
2条回答
  •  悲哀的现实
    2020-11-30 08:30

    Update for Swift 3

    struct PixelData {
        var a: UInt8 = 0
        var r: UInt8 = 0
        var g: UInt8 = 0
        var b: UInt8 = 0
    }
    
    func imageFromBitmap(pixels: [PixelData], width: Int, height: Int) -> UIImage? {
        assert(width > 0)
    
        assert(height > 0)
    
        let pixelDataSize = MemoryLayout.size
        assert(pixelDataSize == 4)
    
        assert(pixels.count == Int(width * height))
    
        let data: Data = pixels.withUnsafeBufferPointer {
            return Data(buffer: $0)
        }
    
        let cfdata = NSData(data: data) as CFData
        let provider: CGDataProvider! = CGDataProvider(data: cfdata)
        if provider == nil {
            print("CGDataProvider is not supposed to be nil")
            return nil
        }
        let cgimage: CGImage! = CGImage(
            width: width,
            height: height,
            bitsPerComponent: 8,
            bitsPerPixel: 32,
            bytesPerRow: width * pixelDataSize,
            space: CGColorSpaceCreateDeviceRGB(),
            bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue),
            provider: provider,
            decode: nil,
            shouldInterpolate: true,
            intent: .defaultIntent
        )
        if cgimage == nil {
            print("CGImage is not supposed to be nil")
            return nil
        }
        return UIImage(cgImage: cgimage)
    }
    

提交回复
热议问题