(IOS)取图片某一点的颜色

if(point.x <0|| point.y <0)returnnil;

CGImageRefimageRef =self.CGImage;

NSUIntegerwidth = CGImageGetWidth(imageRef);

NSUIntegerheight = CGImageGetHeight(imageRef);

if(point.x >= width || point.y >= height)returnnil;

unsignedchar*rawData =malloc(height*width*4);

if(!rawData)returnnil;

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

NSUIntegerbytesPerPixel =4;

NSUIntegerbytesPerRow =bytesPerPixel*width;

NSUIntegerbitsPerComponent =8;

CGContextRef context = CGBitmapContextCreate(rawData,

                                             width,

                                             height,

                                             bitsPerComponent,

                                             bytesPerRow,

                                             colorSpace,

                                             kCGImageAlphaPremultipliedLast

                                             |kCGBitmapByteOrder32Big);

if(!context) {

    free(rawData);

    return nil;

}

CGColorSpaceRelease(colorSpace);

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

CGContextRelease(context);

intbyteIndex = (bytesPerRow * point.y) + point.x * bytesPerPixel;

CGFloatred  = (rawData[byteIndex]    *1.0) /255.0;

CGFloatgreen = (rawData[byteIndex+1] *1.0) /255.0;

CGFloatblue  = (rawData[byteIndex+2] *1.0) /255.0;

CGFloatalpha = (rawData[byteIndex+3] *1.0) /255.0;

UIColor*result =nil;

result = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];

free(rawData);

returnresult;

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容