Skip to content

Instantly share code, notes, and snippets.

@justinHowlett
Created January 23, 2013 18:07
Show Gist options
  • Save justinHowlett/4611132 to your computer and use it in GitHub Desktop.
Save justinHowlett/4611132 to your computer and use it in GitHub Desktop.
Find bottom non-transparent pixels in a UIImage
float bottomNonAlphaPixel(UIImage* inputImage){
float bottomNonAlphaPixel = 0;
float const neighboringPixelThreshold = 4;
CFDataRef imageData = CGDataProviderCopyData(CGImageGetDataProvider(inputImage.CGImage));
const UInt8 *pixels = CFDataGetBytePtr(imageData);
UInt8 alphaThreshold = 20;
int bytesPerPixel = 4;
for(int x = 0; x < inputImage.size.width; x++) {
for(int y = bottomNonAlphaPixel; y < inputImage.size.height; y++) {
int pixelStartIndex = (x + (y * inputImage.size.width)) * bytesPerPixel;
UInt8 alphaVal = pixels[pixelStartIndex];
if (alphaVal>alphaThreshold && y > bottomNonAlphaPixel){
int transparentNeighbors = 0;
//naive neighbor lookup to find outliers
for (int rY = -1; rY<2; rY ++){
for (int rX = -1 ; rX<2; rX ++){
if (rX==0 && rY ==0)continue;
int neighborPixelStartIndex = ((x+rX) + ((y+rY) * inputImage.size.width)) * bytesPerPixel;
UInt8 alphaVal = pixels[neighborPixelStartIndex];
if (alphaVal < alphaThreshold){
transparentNeighbors ++;
}
}
}
if (transparentNeighbors >=neighboringPixelThreshold){
//outlier, disqualify!
}else{
bottomNonAlphaPixel= y;
}
}
}
}
return bottomNonAlphaPixel;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment