简体   繁体   English

Objective-C (iOS),使用 CIFilter 调整图像大小会产生无效输出 (UIImage)

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

I'm trying to resize JPEG image in Objective-C (iOS).我正在尝试在 Objective-C (iOS) 中调整 JPEG 图像的大小。 Input is a JPG file and output should be UIImage .输入是一个 JPG 文件,输出应该是UIImage

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:但输出图像无效( outputImage.size.height is 0 ),在其他处理中导致以下错误:

CGContextDrawImage: invalid context 0x0. CGContextDrawImage:无效的上下文 0x0。 If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.如果要查看回溯,请设置 CG_CONTEXT_SHOW_BACKTRACE 环境变量。 ImageIO: JPEG Empty JPEG image (DNL not supported) ImageIO:JPEG 空 JPEG 图像(不支持 DNL)


Update: 更新:

I don't know, what is wrong with the code above (except the initialization mentioned by Sulthan below - thank him for that).我不知道,上面的代码有什么问题(除了下面 Sulthan 提到的初始化 - 谢谢他)。 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]; CGImageRelease(output_cgimage);

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 .如果图像不是从CIImage初始化的,那么它自己的CIImagenil A safer approach is:更安全的方法是:

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

Also, make sure the image has been loaded successfully from your data.此外,请确保已从您的数据成功加载图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM