I have a masking CGContext
with 2 types of pixels: color and alpha (opaque and transparent pixels). How to calculate percentage of alpha pixels in my context?
Asked
Active
Viewed 993 times
0

Shaik Riyaz
- 11,204
- 7
- 53
- 70

andr111
- 2,982
- 11
- 35
- 45
1 Answers
3
I didn't test it, but this should do the trick - just pass ReportAlphaPercent a CGImageRef:
UIImage *foo; //The image you want to analyze
float alphaPercent = ReportAlphaPercent(foo.CGImage);
float ReportAlphaPercent(CGImageRef imgRef)
{
size_t w = CGImageGetWidth(imgRef);
size_t h = CGImageGetHeight(imgRef);
unsigned char *inImage = malloc(w * h * 4);
memset(inImage, 0, (h * w * 4));
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(inImage, w, h, 8, w * 4, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGContextSetShouldAntialias(context, NO);
CGContextDrawImage(context, CGRectMake(0, 0, w, h), imgRef);
int byteIndex = 0;
int alphaCount = 0;
for(int i = 0; i < (w * h); i++) {
if (inImage[byteIndex + 3]) { // if the alpha value is not 0, count it
alphaCount++;
}
byteIndex += 4;
}
free(inImage);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return (float) alphaCount / (w * h);
}

Alex L
- 8,748
- 5
- 49
- 75

Jeshua Lacock
- 5,730
- 1
- 28
- 58