是否有一种简单的方法可以获得一个二维数组或类似的代表图像像素数据的东西?
我有黑&白色PNG图像,我只想读取某个坐标处的颜色值。例如,颜色值为20/100。
答案 0 :(得分:25)
UIImage上的此类别可能对 Source
有所帮助#import <CoreGraphics/CoreGraphics.h>
#import "UIImage+ColorAtPixel.h"
@implementation UIImage (ColorAtPixel)
- (UIColor *)colorAtPixel:(CGPoint)point {
// Cancel if point is outside image coordinates
if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, self.size.width, self.size.height), point)) {
return nil;
}
// Create a 1x1 pixel byte array and bitmap context to draw the pixel into.
// Reference: http://stackoverflow.com/questions/1042830/retrieving-a-pixel-alpha-value-for-a-uiimage
NSInteger pointX = trunc(point.x);
NSInteger pointY = trunc(point.y);
CGImageRef cgImage = self.CGImage;
NSUInteger width = CGImageGetWidth(cgImage);
NSUInteger height = CGImageGetHeight(cgImage);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
int bytesPerPixel = 4;
int bytesPerRow = bytesPerPixel * 1;
NSUInteger bitsPerComponent = 8;
unsigned char pixelData[4] = { 0, 0, 0, 0 };
CGContextRef context = CGBitmapContextCreate(pixelData,
1,
1,
bitsPerComponent,
bytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextSetBlendMode(context, kCGBlendModeCopy);
// Draw the pixel we are interested in onto the bitmap context
CGContextTranslateCTM(context, -pointX, -pointY);
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, (CGFloat)width, (CGFloat)height), cgImage);
CGContextRelease(context);
// Convert color values [0..255] to floats [0.0..1.0]
CGFloat red = (CGFloat)pixelData[0] / 255.0f;
CGFloat green = (CGFloat)pixelData[1] / 255.0f;
CGFloat blue = (CGFloat)pixelData[2] / 255.0f;
CGFloat alpha = (CGFloat)pixelData[3] / 255.0f;
return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}
@end
答案 1 :(得分:4)
您可以将png放入图像视图,然后使用this method从您将绘制图像的图形上下文中获取像素值。
答案 2 :(得分:2)
为你做的一个课程,并解释了: http://www.markj.net/iphone-uiimage-pixel-color/
答案 3 :(得分:1)
直接方法略微乏味,但这里有:
获取CoreGraphics图片。
CGImageRef cgImage = image.CGImage;
获取“数据提供者”,然后从中获取数据。
NSData * d = [(id)CGDataProviderCopyData(CGImageGetDataProvider(cgImage)) autorelease];
找出数据的格式。
CGImageGetBitmapInfo();
CGImageGetBitsPerComponent();
CGImageGetBitsPerPixel();
CGImageGetBytesPerRow();
找出颜色空间(PNG支持灰度/ RGB /调色板)。
CGImageGetColorSpace()
间接方法是将图像绘制到上下文中(请注意,如果需要任何保证,可能需要指定上下文的字节顺序)并读取字节。
如果您只想要单个像素,则将图像绘制到具有正确矩形的1x1上下文可能会更快
(如(CGRect){{-x,-y},{imgWidth,imgHeight}}
)
这将为您处理色彩空间转换。如果您只想要亮度值,请使用灰度上下文。