Jolinar Jolinar - 4 years ago 287
Objective-C Question

Objective-C (iOS), Image resizing using CIFilter produces invalid output (UIImage)

I'm trying to resize JPEG image in Objective-C (iOS). Input is a JPG file and output should be


I have this code:

// Load image from a file
NSData *imageData = [NSData dataWithContentsOfFile:jpgFile];
UIImage *inputImage = [UIImage imageWithData:imageData];
CIImage *ciImage = inputImage.CIImage;

// Set Lanczos filter
CIFilter *scaleFilter = [CIFilter filterWithName:@"CILanczosScaleTransform"];
[scaleFilter setValue:ciImage forKey:@"inputImage"];
[scaleFilter setValue:[NSNumber numberWithFloat:0.5] forKey:@"inputScale"];
[scaleFilter setValue:[NSNumber numberWithFloat:1.0] forKey:@"inputAspectRatio"];

// Get an output
CIImage *finalImage = [scaleFilter valueForKey:@"outputImage"];
UIImage *outputImage = [[UIImage alloc] initWithCIImage:finalImage];

But the output image is invalid (
outputImage.size.height is 0
), and it causes following errors in an other processing:

CGContextDrawImage: invalid context 0x0. If you want to see the
backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental
variable. ImageIO: JPEG Empty JPEG image (DNL not supported)


I don't know, what is wrong with the code above (except the initialization mentioned by Sulthan below - thank him for that). I used following code at the end (this code works OK):

CIImage *input_ciimage = [[CIImage alloc] initWithImage:inputImage];
CIImage *output_ciimage =
[[CIFilter filterWithName:@"CILanczosScaleTransform" keysAndValues:
kCIInputImageKey, input_ciimage,
kCIInputScaleKey, [NSNumber numberWithFloat:0.5],
nil] outputImage];
CIContext *context = [CIContext contextWithOptions:nil];
CGImageRef output_cgimage = [context createCGImage:output_ciimage fromRect:[output_ciimage extent]];
UIImage *output_uiimage = [UIImage imageWithCGImage:output_cgimage];

Answer Source

This line is the problem:

CIImage *ciImage = inputImage.CIImage

If the image is not initialized from a CIImage then it's own CIImage is nil. A safer approach is:

CIImage *ciImage = [[CIImage alloc] initWithImage:inputImage];

Also, make sure the image has been loaded successfully from your data.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download