Sage Washabaugh
Sage Washabaugh

Reputation: 297

Removing A Core Graphics Filter

I am trying to think of an efficient way to remove a core graphics image filter here is the code for the filter it applies a sepia effect to a UIImage

-(UIImage*)applyFilter {

    CGImageRef inImage = self.CGImage;
    CFDataRef m_dataRef = CGDataProviderCopyData(CGImageGetDataProvider(inImage));
    UInt8* m_pixelBuf = (UInt8*)CFDataGetBytePtr(m_dataRef);

    int length = CFDataGetLength(m_dataRef);

    for (int i=0; i<length; i+=4) {
        filterSepia(m_pixelBuf, i);
    }

    CGContextRef ctx = CGBitmapContextCreate(m_pixelBuf,
                                         CGImageGetWidth(inImage),
                                         CGImageGetHeight(inImage),
                                         CGImageGetBitsPerComponent(inImage),
                                         CGImageGetBytesPerRow(inImage),
                                         CGImageGetColorSpace(inImage),
                                         CGImageGetBitmapInfo(inImage));

    CGImageRef imageRef = CGBitmapContextCreateImage(ctx);
    CGContextRelease(ctx);
    UIImage* finalImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    CFRelease(m_dataRef);
    return finalImage;
}

void filterSepia(UInt8 *pixelBuf, UInt32 offset) {

    int r = offset;
int g = offset+1;
int b = offset+2;

int red = pixelBuf[r];
int green = pixelBuf[g];
int blue = pixelBuf[b];

    pixelBuf[r] = SAFECOLOR((red*0.393)+(green*0.769)+(blue*0.189));
    pixelBuf[g] = SAFECOLOR((red*0.349)+(green*0.686)+(blue*0.168));
    pixelBuf[b] = SAFECOLOR((red*0.272)+(green*0.534)+(blue*131));
}

Now what I want to remove this effect or something like it efficiently I could do something like this when a toggle button is pressed

In the header:

#define SAFECOLOR(color) MIN(255, MAX(0,color))
BOOL toggleOn;
@property (nonatomic, retain)UIImage* image;

In the implementation:

-(IBAction)sepiaButton:(id)sender {

    UIImage* original = image;
    if (toggleOn) {
        [image applyFilter];
    } else {
        image = original;
    }
    toggleOn =! toggleOn
}

But as multiple image filters are applied could this become inefficient or is there a better way to do this?

Upvotes: 0

Views: 219

Answers (1)

Mundi
Mundi

Reputation: 80273

Why keep generating the same images and not instead pre-render them? Keep a copy of the original version around and simply hide overlaid views.

Upvotes: 1

Related Questions