Objective-c - Getting least used and most used color in a image

后端 未结 3 1527
南旧
南旧 2020-12-07 10:34

Im trying to get the least used color, and the most used color from MP3 file\'s album artwork for a music playing application. I need the colors to do an effect like the new

3条回答
  •  执念已碎
    2020-12-07 10:52

    Not sure about finding most color or least color, but here is a method to find out the average color.

    - (UIColor *)averageColor {
    
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        unsigned char rgba[4];
        CGContextRef context = CGBitmapContextCreate(rgba, 1, 1, 8, 4, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    
        CGContextDrawImage(context, CGRectMake(0, 0, 1, 1), self.CGImage);
        CGColorSpaceRelease(colorSpace);
        CGContextRelease(context);  
    
        if(rgba[3] > 0) {
            CGFloat alpha = ((CGFloat)rgba[3])/255.0;
            CGFloat multiplier = alpha/255.0;
            return [UIColor colorWithRed:((CGFloat)rgba[0])*multiplier
                                   green:((CGFloat)rgba[1])*multiplier
                                    blue:((CGFloat)rgba[2])*multiplier
                                   alpha:alpha];
        }
        else {
            return [UIColor colorWithRed:((CGFloat)rgba[0])/255.0
                                   green:((CGFloat)rgba[1])/255.0
                                    blue:((CGFloat)rgba[2])/255.0
                                   alpha:((CGFloat)rgba[3])/255.0];
        }
    }
    

    You can probably follow a similar approach to find out the most used color.

    Also check this answer about counting red color pixels in an image.

提交回复
热议问题