how to get the alpha channel alone in IOS?

不想你离开。 提交于 2019-12-05 20:55:53

Check if this works. This function returns you autoreleased alpha image.

- (UIImage*)seperatAlphaFromImage:(UIImage*)pngImage writeToFile:(NSString*)path compressionQuality:(float)value0To1
{    
CGRect imageRect = CGRectMake(0, 0, pngImage.size.width, pngImage.size.height);

//Pixel Buffer
uint32_t* piPixels = (uint32_t*)malloc(imageRect.size.width * imageRect.size.height * sizeof(uint32_t));
if (piPixels == NULL)
{
    return nil;
}
memset(piPixels, 0, imageRect.size.width * imageRect.size.height * sizeof(uint32_t));

//Drawing image in the buffer
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(piPixels, imageRect.size.width, imageRect.size.height, 8, sizeof(uint32_t) * imageRect.size.width, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast);

CGContextDrawImage(context, imageRect, pngImage.CGImage);

//Copying the alpha values to the red values of the image and setting the alpha to 1
for (uint32_t y = 0; y < imageRect.size.height; y++) 
{
    for (uint32_t x = 0; x < imageRect.size.width; x++)
    {
        uint8_t* rgbaValues = (uint8_t*)&piPixels[y * (uint32_t)imageRect.size.width + x];

        //alpha = 0, red = 1, green = 2, blue = 3.

        rgbaValues[0] = rgbaValues[0];
        rgbaValues[1] = rgbaValues[0];
        rgbaValues[2] = rgbaValues[0];
        rgbaValues[3] = rgbaValues[0];
    }
}

//Creating image whose red values will preserve the alpha values
CGImageRef newCGImage = CGBitmapContextCreateImage(context);
UIImage* newImage = [[[UIImage alloc] initWithCGImage:newCGImage]autorelease];
CGImageRelease(newCGImage);

return newImage;    
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!