gpt4 book ai didi

ios - UIImageJPEGRepresentation 返回 nil

转载 作者:IT王子 更新时间:2023-10-29 05:16:39 32 4
gpt4 key购买 nike

我正在使用 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's answer :

// 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)
}

最佳答案

UIImageJPEGRepresentation 似乎使用了 UIImageCGImage 属性。问题是,当您使用 CIImage 初始化 UIImage 时,该属性为 nil

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

最后更新 Swift 5.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)
}

关于ios - UIImageJPEGRepresentation 返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29732886/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com