我正在检查UIImage是更暗还是更白。我想使用这种方法,但只检查图像底部的第三部分,而不是全部。我想知道如何更改它来检查,我对像素的东西不太熟悉。
BOOL isDarkImage(UIImage* inputImage){
BOOL isDark = FALSE;
CFDataRef imageData = CGDataProviderCopyData(CGImageGetDataProvider(inputImage.CGImage));
const UInt8 *pixels = CFDataGetBytePtr(imageData);
int darkPixels = 0;
long length = CFDataGetLength(imageData);
int const darkPixelThreshold = (inputImage.size.width*inputImage.size.height)*.25;
//should i change here the length ?
for(int i=0; i<length; i+=4)
{
int r = pixels[i];
int g = pixels[i+1];
int b = pixels[i+2];
//luminance calculation gives more weight to r and b for human eyes
float luminance = (0.299*r + 0.587*g + 0.114*b);
if (luminance<150) darkPixels ++;
}
if (darkPixels >= darkPixelThreshold)
isDark = YES;
我可以只裁剪图像的那一部分,但这不是有效的方法,而且浪费时间。
这里标记为正确的解决方案是一种更周到的获取像素数据的方法(对不同格式更宽容),还演示了如何寻址像素。通过小的调整,您可以获得图像的底部,如下所示:
+ (NSArray*)getRGBAsFromImage:(UIImage*)image
atX:(int)xx
andY:(int)yy
toX:(int)toX
toY:(int)toY {
// ...
int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
int byteIndexEnd = (bytesPerRow * toY) + toX * bytesPerPixel;
while (byteIndex < byteIndexEnd) {
// contents of the loop remain the same
// ...
}
要获得图像的底部三分之一,请使用分别等于图像宽度和高度的xx=0
、yy=2.0*image.height/3.0
、toX
和toY
来调用此函数。循环返回数组中的颜色,并根据帖子的建议计算亮度。