【问题标题】:average color value of UIImage in Objective-CObjective-C中UIImage的平均颜色值
【发布时间】:2011-07-30 13:04:52
【问题描述】:

我需要目标 c 中图像的平均颜色值。我想创建它的颜色渐变。 有人有想法吗?

【问题讨论】:

  • 请参阅this answer 了解优化方法。它大约快四倍。

标签: objective-c iphone-sdk-3.0


【解决方案1】:

有一种方法可以从 Image 创建平均颜色。

[UIColor colorWithAverageColorFromImage:(UIImage *)image];

【讨论】:

  • 不,没有(ಥ﹏ಥ)
【解决方案2】:

这是一个我还没有测试过的实验代码。

struct pixel {
    unsigned char r, g, b, a;
};

- (UIColor*) getDominantColor:(UIImage*)image
{
    NSUInteger red = 0;
    NSUInteger green = 0;
    NSUInteger blue = 0;


    // Allocate a buffer big enough to hold all the pixels

    struct pixel* pixels = (struct pixel*) calloc(1, image.size.width * image.size.height * sizeof(struct pixel));
    if (pixels != nil)
    {

        CGContextRef context = CGBitmapContextCreate(
                                                 (void*) pixels,
                                                 image.size.width,
                                                 image.size.height,
                                                 8,
                                                 image.size.width * 4,
                                                 CGImageGetColorSpace(image.CGImage),
                                                 kCGImageAlphaPremultipliedLast
                                                 );

        if (context != NULL)
        {
            // Draw the image in the bitmap

            CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, image.size.width, image.size.height), image.CGImage);

            // Now that we have the image drawn in our own buffer, we can loop over the pixels to
            // process it. This simple case simply counts all pixels that have a pure red component.

            // There are probably more efficient and interesting ways to do this. But the important
            // part is that the pixels buffer can be read directly.

            NSUInteger numberOfPixels = image.size.width * image.size.height;
            for (int i=0; i<numberOfPixels; i++) {
                red += pixels[i].r;
                green += pixels[i].g;
                blue += pixels[i].b;
            }


            red /= numberOfPixels;
            green /= numberOfPixels;
            blue/= numberOfPixels;


            CGContextRelease(context);
        }

        free(pixels);
    }
    return [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:1.0f];
}

您可以使用这种方法,例如;

-(void)doSomething
{
    UIImage *image = [UIImage imageNamed:@"someImage.png"];
    UIColor *dominantColor = [self getDominantColor:image];
}

我希望这对你有用。

您也可以在 UIImage 中使用类别实现。为对象编写一些实用程序的更好方法:)

编辑:修复了while()中的错误。

【讨论】:

  • 谢谢,它适用于明亮的图像,但对于较暗的图像,我只能得到黑色。喜欢这个:alles-iphone.de/CONTENT/content-pre1/72207-1.jpg。值pixels->r,pixels->g 和pixels->b 永远不会高于“20”。
  • 请参阅this answer 了解优化方法。它大约快四倍。
  • 但是我需要一些主色,你能帮我吗
  • 主色的数量是什么意思?
  • 平均颜色!=主色。图像中可能不存在平均颜色。不是主色(虽然可能是感知上的主色)。