Last active
July 9, 2024 11:53
-
-
Save justinHowlett/4611988 to your computer and use it in GitHub Desktop.
Determine if a UIImage is generally dark or generally light
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
BOOL isDarkImage(UIImage* inputImage){ | |
BOOL isDark = FALSE; | |
CFDataRef imageData = CGDataProviderCopyData(CGImageGetDataProvider(inputImage.CGImage)); | |
const UInt8 *pixels = CFDataGetBytePtr(imageData); | |
int darkPixels = 0; | |
int length = CFDataGetLength(imageData); | |
int const darkPixelThreshold = (inputImage.size.width*inputImage.size.height)*.45; | |
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; | |
CFRelease(imageData); | |
return isDark; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have created Swift categories for UIImage and CGImage based on this method. For anyone who is interested: ImageDarkness.swift