Created
May 2, 2016 23:50
-
-
Save codinfox/c1f58ddfb20fa686d46932112716c00a to your computer and use it in GitHub Desktop.
Convert UIImage to RGB values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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