UIImageJPEGRepresentation returns 无

UIImageJPEGRepresentation returns nil

我正在使用 CIFilters 将图像转换为灰度并应用一些图像处理效果。在 UIImageView 中显示输出是可行的;图像显示并按预期进行了修改。

但是,每次调用 UIImageJPEGRepresentation 似乎都return 没有数据。它永远行不通。 使用原始彩色图像调用 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!?

编辑:这是工作代码,基于:

// 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。

UIImageJPEGRepresentation好像用了CGImage属性的UIImage。问题是,当你用 CIImage 初始化 UIImage 时,属性 是 nil.

我的解决方案是在 UIImageJPEGRepresentation 调用之前添加以下块:

最后更新Swift5.1

if image.cgImage == nil {
    guard 
        let ciImage = image.ciImage, 
        let cgImage = CIContext(options: nil).createCGImage(ciImage, from: ciImage.extent) 
    else { 
         return nil 
    }

    image = UIImage(cgImage: cgImage)
}

丹尼尔的回答很有效。在他的答案下方转换为在 Swift4 中使用。

Swift4

    if image?.cgImage == nil {
        guard let ciImage = image?.ciImage, let cgImage = CIContext(options: nil).createCGImage(ciImage, from: ciImage.extent) else { return }

        image = UIImage(cgImage: cgImage)
    }