Get pixel data as array from UIImage/CGImage in swift

后端 未结 3 1579
梦毁少年i
梦毁少年i 2020-12-01 12:14

I have an app so far that allows the user to free draw (like a sketch pad) on a UIImageView element.

I want to get the raw RGB pixel data (as <

3条回答
  •  离开以前
    2020-12-01 13:15

    Please try this. This worked right for me.

    func pixelValues(fromCGImage imageRef: CGImage?) -> [UInt8]?
        {
            var width = 0
            var height = 0
            var pixelValues: [UInt8]?
    
            if let imageRef = imageRef {
                width = imageRef.width
                height = imageRef.height
                let bitsPerComponent = imageRef.bitsPerComponent
                let bytesPerRow = imageRef.bytesPerRow
                let totalBytes = height * bytesPerRow
                let bitmapInfo = imageRef.bitmapInfo
    
                let colorSpace = CGColorSpaceCreateDeviceRGB()
                var intensities = [UInt8](repeating: 0, count: totalBytes)
    
                let contextRef = CGContext(data: &intensities,
                                          width: width,
                                         height: height,
                               bitsPerComponent: bitsPerComponent,
                                    bytesPerRow: bytesPerRow,
                                          space: colorSpace,
                                     bitmapInfo: bitmapInfo.rawValue)
                contextRef?.draw(imageRef, in: CGRect(x: 0.0, y: 0.0, width: CGFloat(width), height: CGFloat(height)))
    
                pixelValues = intensities
            }
    
            return pixelValues
    }
    

提交回复
热议问题