Skip to content

Instantly share code, notes, and snippets.

@giulio92
Last active December 4, 2018 09:13
Show Gist options
  • Save giulio92/69e4f74217422154bb25d2a35d6710f8 to your computer and use it in GitHub Desktop.
Save giulio92/69e4f74217422154bb25d2a35d6710f8 to your computer and use it in GitHub Desktop.
Get pixel color from UIImage in Swift
func getColorForPixel(image:CGImageRef, point:CGPoint) -> UIColor {
let imageWidth = CGImageGetWidth(image)
let imageHeight = CGImageGetHeight(image)
let imageRect = CGRect(x: 0, y: 0, width: imageWidth, height: imageHeight)
let bitmapBytesForRow = Int(imageWidth * 4)
let bitmapByteCount = bitmapBytesForRow * Int(imageHeight)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapMemory = malloc(bitmapByteCount)
let bitmapInformation = CGImageAlphaInfo.PremultipliedFirst.rawValue
let colorContext = CGBitmapContextCreate(bitmapMemory, imageWidth, imageHeight, 8, bitmapBytesForRow, colorSpace, bitmapInformation)
CGContextClearRect(colorContext, imageRect)
CGContextDrawImage(colorContext, imageRect, image)
let data = CGBitmapContextGetData(colorContext)
let dataType = UnsafePointer<UInt8>(data)
let offset = 4 * (Int(imageWidth) * Int(point.y)) + Int(point.x)
let redComponent = CGFloat(dataType[offset + 1])/255.0
let greenComponent = CGFloat(dataType[offset + 2])/255.0
let blueComponent = CGFloat(dataType[offset + 3])/255.0
return UIColor(red: redComponent, green: greenComponent, blue: blueComponent, alpha: 1.0)
}
@Cyberbeni
Copy link

you forgot to call free(bitmapMemory)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment