Skip to content

Instantly share code, notes, and snippets.

@aleclarson
Created January 30, 2021 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aleclarson/460dfc66a1a137582cd4b9c13b2f9315 to your computer and use it in GitHub Desktop.
Save aleclarson/460dfc66a1a137582cd4b9c13b2f9315 to your computer and use it in GitHub Desktop.
Alpha mask from CGImage
CGImageRef createAlphaMask(CGImageRef inputImage) {
int width = (int)CGImageGetWidth(inputImage);
int height = (int)CGImageGetHeight(inputImage);
int bytesPerRow = (int)CGImageGetBytesPerRow(inputImage);
CGColorSpaceRef colorSpace = CGImageGetColorSpace(inputImage);
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(inputImage);
unsigned char *data = (unsigned char *)calloc(bytesPerRow * height, 1);
CGContextRef ctx = CGBitmapContextCreate(data,
width,
height,
8,
bytesPerRow,
colorSpace,
bitmapInfo);
if (!ctx) {
return nil;
}
int alphaIndex = bitmapInfo & (kCGImageAlphaFirst | kCGImageAlphaPremultipliedFirst)
? 0
: 3;
if (bitmapInfo & kCGImageByteOrder32Little) {
alphaIndex = 3 - alphaIndex;
}
CGDataProviderRef inputProvider = CGImageGetDataProvider(inputImage);
NSData *inputData = (__bridge NSData *)CGDataProviderCopyData(inputProvider);
unsigned char *inputBytes = (unsigned char *)inputData.bytes;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int offset = (x + y * width) * 4;
int alpha = inputBytes[offset + alphaIndex];
if (alpha > 0) {
alpha = 255;
}
data[offset + 0] = alphaIndex == 0 ? alpha : 0;
data[offset + 1] = 0;
data[offset + 2] = 0;
data[offset + 3] = alphaIndex == 3 ? alpha : 0;
}
}
CGImageRef image = CGBitmapContextCreateImage(ctx);
CGContextRelease(ctx);
free(data);
return image;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment