Skip to content

Instantly share code, notes, and snippets.

@codinfox
Created May 2, 2016 23:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codinfox/c1f58ddfb20fa686d46932112716c00a to your computer and use it in GitHub Desktop.
Save codinfox/c1f58ddfb20fa686d46932112716c00a to your computer and use it in GitHub Desktop.
Convert UIImage to RGB values
let inputCGImage = UIImage(contentsOfFile: "<filename>")!.CGImage
let width = CGImageGetWidth(inputCGImage)
let height = CGImageGetHeight(inputCGImage)
let bytesPerPixel = 4
let bytesPerRow = bytesPerPixel * width
let bitsPerComponent = 8
let pixels = UnsafeMutablePointer<UInt32>(calloc(height * width, sizeof(UInt32)))
let colorSpace = CGColorSpaceCreateDeviceRGB()
let context = CGBitmapContextCreate(pixels, width, height, bitsPerComponent, bytesPerRow, colorSpace, CGImageAlphaInfo.PremultipliedFirst.rawValue)
CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), inputCGImage)
let dataType = UnsafePointer<UInt8>(pixels)
for j in 0 ..< height {
for i in 0 ..< width {
let offset = 4*((Int(width) * Int(j)) + Int(i))
let alphaValue = dataType[offset] as UInt8
let redColor = dataType[offset+1] as UInt8
let greenColor = dataType[offset+2] as UInt8
let blueColor = dataType[offset+3] as UInt8
}
}
free(pixels)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment