views:

495

answers:

2

I am trying to do an iteration on pixels to change the RGBA values of a UIImage without using OpenGL. I tried testing out iteration performance using the below code but was very displeased. It seemed like I could only get a few thousand iterations per second. And for a UIImage with several hundred thousand pixels, this would take way TOO LONG...Anybody have any suggestions on how to improve performance or how long operations like these should normally take?

-(UIImage*)modifyPixels:(UIImage*)originalImage
{
    NSData* pixelData = (NSData*)CGDataProviderCopyData(CGImageGetDataProvider(originalImage.CGImage));
    void* pixelBytes = [pixelData bytes];

    // Take away the red pixel, assuming 32-bit RGBA
    for(int i = 0; i < [pixelData length]; i += 4) {
        NSLog(@" %ith iteration (%i / %i / %i / %i)", i, pixelData[i], pixelData[i+1], pixelData[i+2], pixelData[i+3]);
    }

    //NSData* newPixelData = [NSData dataWithBytes:pixelBytes length:[pixelData length]];
    //UIImage* newImage = [UIImage imageWithData:newPixelData]; 

    return originalImage;    
}
+2  A: 

Your NSLog statement will slow the image iteration process down considerably. A good test would be to invert the image instead of logging out the pixel data. Also calculating the data length for each iteration will also slow things down. Cache the length in a local variable and use that instead.

Bruce Johnson
Agreed. NSLog() can be incredibly slow.
Rob Napier
Thanks. That helped alot!
RexOnRoids
+3  A: 

Don't invoke [pixelData length] in the loop. The compiler can't know the result of this message is constant, so it'll invoke the method instead.

Nicholas Riley
This is a very good tip; I've seen even experienced developers overlook this.
rpetrich