UIImage+GPUImage Category

GPUImage, while a great OpenGL based camera and video library, has its eccentricities. Here is a nice way to easily save an image out of a still camera using a filter.

#import "UIImage+GPUImage.h"

@implementation UIImage (GPUImage)

+(void)imageFromStillCamera:(GPUImageStillCamera*)stillCamera withFilter:(GPUImageFilter*)filter withCompletion:(USPImageFromGPUCameraCompletionBlock)completion andError:(USPImageFromGPUCameraErrorBlock)errorBlock{
     
   // Block for filtering the image.
   void (^handler)(NSData *processedPNG, NSError *error) = ^(NSData *processedPNG, NSError *error) {
       
       UIImage *pngImage = [UIImage imageWithData:processedPNG];
       if(error != nil){
           completion(pngImage);
       }  else {
           errorBlock(error);
       }
   };

   // Process the image.
   [stillCamera capturePhotoAsPNGProcessedUpToFilter:filter
                                    withCompletionHandler:handler];
}

+(void)saveImageFromStillCamera:(GPUImageStillCamera*)stillCamera withFilter:(GPUImageFilter*)filter withCompletion:(USPImageFromGPUCameraCompletionBlock)completion andError:(USPImageFromGPUCameraErrorBlock)errorBlock{
    
    // Block for filtering the image.
    void (^handler)(NSData *processedPNG, NSError *error) = ^(NSData *processedPNG, NSError *error) {
        
        UIImage *pngImage = [UIImage imageWithData:processedPNG];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        
        NSError *error2 = nil;
        if (![processedPNG writeToFile:[documentsDirectory stringByAppendingPathComponent:@"FilteredPhoto.png"] options:NSAtomicWrite error:&error2])
        {
            completion(pngImage);
        } else{
            errorBlock(error);
        }
    };
    
    // Process the image.
    [stillCamera capturePhotoAsPNGProcessedUpToFilter:filter
                                withCompletionHandler:handler];
}
@end