iOS获取图片主色或者突出颜色

2022-03-03  本文已影响0人  CodingTom

获取图片中突出的颜色

https://github.com/tangdiforx/iOSPalette

pod 'iOSPalette'

获取图片中占比最多的颜色


/// 根据图片获取图片的主色调
/// @param image 图片
+ (UIColor *)GetImageMostColor:(UIImage *)image
{
    int bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
    //第一步 先把图片缩小 加快计算速度. 但越小结果误差可能越大
    CGSize thumbSize = CGSizeMake(image.size.width / 6, image.size.height / 6);

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL,
                                                 thumbSize.width,
                                                 thumbSize.height,
                                                 8,//bits per component
                                                 thumbSize.width * 4,
                                                 colorSpace,
                                                 bitmapInfo);

    CGRect drawRect = CGRectMake(0, 0, thumbSize.width, thumbSize.height);
    CGContextDrawImage(context, drawRect, image.CGImage);
    CGColorSpaceRelease(colorSpace);

    //第二步 取每个点的像素值
    unsigned char *data = CGBitmapContextGetData(context);
    if (data == NULL) return nil;
    NSCountedSet *cls = [NSCountedSet setWithCapacity:thumbSize.width * thumbSize.height];

    for (int x = 0; x < thumbSize.width; x++) {
        for (int y = 0; y < thumbSize.height; y++) {
            int offset = 4 * (x * y);
            int red = data[offset];
            int green = data[offset + 1];
            int blue = data[offset + 2];
            int alpha =  data[offset + 3];
            if (alpha > 0) {//去除透明
                if (red == 255 && green == 255 && blue == 255) {//去除白色
                } else {
                    NSArray *clr = @[@(red), @(green), @(blue), @(alpha)];
                    [cls addObject:clr];
                }
            }
        }
    }
    CGContextRelease(context);
    //第三步 找到出现次数最多的那个颜色
    NSEnumerator *enumerator = [cls objectEnumerator];
    NSArray *currentColorArray = nil;
    NSArray *maxColorArray = nil;
    NSUInteger maxCount = 0;
    while ((currentColorArray = [enumerator nextObject]) != nil) {
        NSUInteger tmpCount = [cls countForObject:currentColorArray];
        if (tmpCount < maxCount) continue;
        maxCount = tmpCount;
        maxColorArray = currentColorArray;
    }
    return [UIColor colorWithRed:([maxColorArray[0] intValue] / 255.0f)
                           green:([maxColorArray[1] intValue] / 255.0f)
                            blue:([maxColorArray[2] intValue] / 255.0f)
                           alpha:([maxColorArray[3] intValue] / 255.0f)];
}

上一篇下一篇

猜你喜欢

热点阅读