iPhone:如何获取图像每个像素的颜色? [英] iPhone : How to get colour of each pixel of an image?

查看:137
本文介绍了iPhone:如何获取图像每个像素的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取图像的所有单个像素的颜色。
要详细说明
假设我有一个名为 SampleImage的图像,具有400 x 400像素
基本上,我想从 SampleImage创建一个网格400 x 400正方形,每个正方形填充有与 SampleImage中特定像素相对应的颜色。

I want to get color of all the individual pixels of an image. To elaborate Let say I have an image named "SampleImage" having 400 x 400 pixels Basically I want to create a grid from 'SampleImage' which will have 400 x 400 squares each filled with color corresponding to the specific pixel in 'SampleImage'.

我知道这有点抽象,但是我对iOS不熟悉,所以不要不知道从哪里开始。
预先感谢!

I know this is a little abstract, but I am novice in iOS and don't know where to start from. Thanks in advance!

推荐答案

这段代码对我来说完美无缺-:

This code worked flawlessly for me -:

    - (NSArray*)getRGBAsFromImage:(UIImage*)image atX:(int)xx andY:(int)yy count:(int)count{
    NSMutableArray *result = [NSMutableArray arrayWithCapacity:count];

    // First get the image into your data buffer
    CGImageRef imageRef = [image CGImage];
    NSUInteger width = CGImageGetWidth(imageRef);
    NSUInteger height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));
    NSUInteger bytesPerPixel = 4;
    NSUInteger bytesPerRow = bytesPerPixel * width;
    NSUInteger bitsPerComponent = 8;
    CGContextRef context = CGBitmapContextCreate(rawData, width, height,
                                                 bitsPerComponent, bytesPerRow, colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);

    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
    CGContextRelease(context);

    // Now your rawData contains the image data in the RGBA8888 pixel format.
    int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
    for (int ii = 0 ; ii < count ; ++ii)
    {
        CGFloat red   = (rawData[byteIndex]     * 1.0) / 255.0;
        CGFloat green = (rawData[byteIndex + 1] * 1.0) / 255.0;
        CGFloat blue  = (rawData[byteIndex + 2] * 1.0) / 255.0;
        CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.0;
        byteIndex += 4;

        UIColor *acolor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
        [result addObject:acolor];
    }

    free(rawData);
    return result;
}

这篇关于iPhone:如何获取图像每个像素的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆