CMOS
CMOS

Reputation: 2917

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?

Upvotes: 0

Views: 2722

Answers (2)

Kurt Pfeifle
Kurt Pfeifle

Reputation: 90263

You can use ImageMagick's API to remove same-color space from image edges.

On the ImageMagick command line, it is as easy as:

convert input.jpg -trim +repage output.png

This -trim operation will automatically remove pixel rows and columns until it meets a pixel that is no longer the same color as the outmost rows/columns.

If your outlaying pixels do not use the exactly same colors, you can add a 'fuzz factor' with -fuzz X%. This will remove all pixels which are within a color distance of X%:

convert input.tiff -trim -fuzz 5% +repage output.gif
convert input.png  -trim -fuzz 9% +repage output.png

(As you can see, the very same command can autodetect requested input and output file formats and transform between them too, if you need that.)

Usually, what you can achieve via the ImageMagick command line, you can also achieve in your own programs when using the API.

Here is a list with all currently available API interfaces. It contains the links to the specific web resources:

Caution: Not all of these APIs are equally well developed, maintained or complete.

Upvotes: 0

JustAnotherCoder
JustAnotherCoder

Reputation: 2575

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];

Upvotes: 4

Related Questions