iOS图像主色提取算法——单像素压缩
2018-06-21 本文已影响34人
Stroman
总述
这是基于iOS平台的,用Objective-C实现的算法,是一个UIColor的类别。具体做法是,将图片压缩成1个像素点,提取这个像素的颜色,作为该图片的主色。
评价
速度最快,最简单粗暴的做法。
实现
- (UIColor *)getMainColor {
UIGraphicsBeginImageContextWithOptions(CGSizeMake(1.0f, 1.0f), NO, 1.0f);
[self drawInRect:CGRectMake(0, 0, 1, 1)];
UIImage *tempImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRef cgTempImage = tempImage.CGImage;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
int bytesPerPixcel = 4;
int bytesPerRow = bytesPerPixcel * 1;
NSUInteger bitsPerChannel = 8;
unsigned char pixelData[4] = {0};
CGContextRef context = CGBitmapContextCreate(pixelData,
1,
1,
bitsPerChannel,
bytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextSetBlendMode(context, kCGBlendModeCopy);
CGContextDrawImage(context, CGRectMake(0, 0, 1, 1), cgTempImage);
CGContextRelease(context);
CGFloat redFloat = pixelData[0];
redFloat /= 255.0f;
CGFloat greenFloat = pixelData[1];
greenFloat /= 255.0f;
CGFloat blueFloat = pixelData[2];
blueFloat /= 255.0f;
CGFloat alphaFloat = pixelData[3];
alphaFloat /= 255.0f;
return [UIColor colorWithRed:redFloat green:greenFloat blue:blueFloat alpha:alphaFloat];
}