Skip to content

Instantly share code, notes, and snippets.

@dhavaln
Created September 4, 2015 10:13
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dhavaln/d28d026e1a427192f8af to your computer and use it in GitHub Desktop.
Save dhavaln/d28d026e1a427192f8af to your computer and use it in GitHub Desktop.
Swift / iOS - Extract Color from Image
func extractColor(image: UIImage){
let pixel = UnsafeMutablePointer<CUnsignedChar>.alloc(4)
let colorSpace:CGColorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
let context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, bitmapInfo)
CGContextDrawImage(context, CGRectMake(0, 0, 1, 1), image.CGImage)
var color: UIColor? = nil
if pixel[3] > 0 {
var alpha:CGFloat = CGFloat(pixel[3]) / 255.0
var multiplier:CGFloat = alpha / 255.0
color = UIColor(red: CGFloat(pixel[0]) * multiplier, green: CGFloat(pixel[1]) * multiplier, blue: CGFloat(pixel[2]) * multiplier, alpha: alpha)
}else{
color = UIColor(red: CGFloat(pixel[0]) / 255.0, green: CGFloat(pixel[1]) / 255.0, blue: CGFloat(pixel[2]) / 255.0, alpha: CGFloat(pixel[3]) / 255.0)
}
if color != nil {
println( self.toHexString(color!) )
}
pixel.dealloc(4)
}
func toHexString(color: UIColor) -> String {
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
color.getRed(&r, green: &g, blue: &b, alpha: &a)
let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
return String(format:"#%06x", rgb)
}
@dhavaln
Copy link
Author

dhavaln commented Sep 4, 2015

I had a case to extract vibrant color from the current camera capture. So capturing the camera image was fine but extracting the color took a while to I put the final working function here.

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