Created
September 4, 2015 10:13
-
-
Save dhavaln/d28d026e1a427192f8af to your computer and use it in GitHub Desktop.
Swift / iOS - Extract Color from Image
This file contains hidden or 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
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.