我正在使用CIFilters将图像转换为灰度并应用一些图像处理效果。在UIImageView中显示输出有效;图像将显示,并且已按预期进行了修改。
但是,每次调用UIImageJPEGRepresentation似乎都不返回任何数据。它永远都行不通。使用原始彩色图像调用UIImageJPEGRepresentation效果很好。
这里发生了什么?为什么在显示图像时jpeg转换会失败?不会引发任何异常(设置异常断点,不会命中),并且控制台中不会显示任何消息。
let _cicontext = CIContext(options:nil) // Set up grayscale and blur filters: let grayIze = CIFilter(name: "CIColorControls") let blur = CIFilter(name: "CIGaussianBlur") grayIze.setValue(0, forKey:kCIInputSaturationKey) grayIze.setValue(0.5, forKey: kCIInputBrightnessKey) blur.setValue(4, forKey: kCIInputRadiusKey) // Go! let originalImage = CIImage(image: colorImageThatDefinitelyExists) grayIze.setValue(originalImage, forKey: kCIInputImageKey) blur.setValue(grayIze.outputImage, forKey: kCIInputImageKey) let output = UIImage(CIImage: blur.outputImage) let imageData: NSData? = UIImageJPEGRepresentation(output, 1.0) // Returns nil!?
编辑:这是基于Arbitur的答案的工作代码:
// Define an image context at the class level, which will only be initialized once: static let imageContext = CIContext(options:nil) // And here's the updated code in a function: class func convertToGrayscale(image: UIImage)->UIImage? { // Set up grayscale and blur filters: let filter1_grayIze = CIFilter(name: "CIColorControls") let filter2_blur = CIFilter(name: "CIGaussianBlur") filter1_grayIze.setValue(0, forKey:kCIInputSaturationKey) filter1_grayIze.setValue(0.5, forKey: kCIInputBrightnessKey) filter2_blur.setValue(4, forKey: kCIInputRadiusKey) // Go! let originalImage = CIImage(image: image) filter1_grayIze.setValue(originalImage, forKey: kCIInputImageKey) filter2_blur.setValue(filter1_grayIze.outputImage, forKey: kCIInputImageKey) let outputCIImage = filter2_blur.outputImage let temp:CGImageRef = imageContext.createCGImage(outputCIImage, fromRect: outputCIImage.extent()) let ret = UIImage(CGImage: temp) return ret } // And finally, the function call: if let grayImage = ProfileImage.convertToGrayscale(colorImage) { let imageData: NSData? = UIImageJPEGRepresentation(grayImage, 1.0) }
我之前遇到过CIImage问题,要解决此问题,我先用CIImage制作了CGImage,然后再用CGImage制作了UIImage。