Search code examples
iosobjective-cxcodeimagemasking

Xcode remove color from image programmatically?


So I have an app where you move images around in certain positions and layer them. Its coming along well but an issue I keep running into is a lot of my images have white spaces around them (they use to be jpgs), the whitespace is always hexcode #FFFFFF pure whitespace, so I was wondering is there a way in objective-c to mask all of a hexcode in an image? I would manually edit the images but there are thousands of them from a third party. Any ideas?


Solution

  • I found this awesome method here that you can place in your current .h file:

    +(UIImage *)changeWhiteColorTransparent: (UIImage *)image
    {
        CGImageRef rawImageRef=image.CGImage;
    
        const float colorMasking[6] = {222, 255, 222, 255, 222, 255};
    
        UIGraphicsBeginImageContext(image.size);
        CGImageRef maskedImageRef=CGImageCreateWithMaskingColors(rawImageRef, colorMasking);
        {
            //if in iphone
            CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0.0, image.size.height);
            CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0); 
        }
    
        CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, image.size.width, image.size.height), maskedImageRef);
        UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
        CGImageRelease(maskedImageRef);
        UIGraphicsEndImageContext();    
        return result;
    }
    

    So simply pass your image to this method like so:

    UIImage *newImage = [self changeWhiteColorTransparent: yourOldImage];