Getting a UIImage
from a CIImgae
via UIImage(ciImage:)
seems to be a very old problem, which still seems to be an issue. Here is an old thread on stackoverflow which presents the same problem: old thread
I would have guessed that this problem should be fixed 6 major releases of iOS (I currently run the code for iOS 12.0), but it does not seem to be the case. Here is a sample playground code for you to try out and reproduce the problem:
import Foundation
import UIKit
import PlaygroundSupport
// extend UIImage to support cunstruction of solid color images
extension UIImage {
public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1), contentScaleFactor: CGFloat = UIScreen.main.scale) {
let rect = CGRect(origin: CGPoint.zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, contentScaleFactor)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage, scale: contentScaleFactor, orientation: .up)
}
}
let uIImage = UIImage(color: UIColor.red, size: CGSize(width: 100.0, height: 100.0), contentScaleFactor: 1.0)!
let cIImage = CIImage(image: uIImage)!
let finalUIImage = UIImage(ciImage: cIImage)
let imageView = UIImageView(image: finalUIImage)
PlaygroundPage.current.liveView = imageView
Where the line let finalUIImage = UIImage(ciImage: cIImage)
yields the error
Failed to convert UIImage to png
As stated in the answer to the previously mentioned old post on stackoverflow replacing let finalUIImage = UIImage(ciImage: cIImage)
with
let context = CIContext()
let finalCGImage = context.createCGImage(cIImage, from: cIImage.extent)!
let finalUIImage = UIImage(cgImage: finalCGImage)
works.
I am posting this question because I want to know:
- Can you reproduce this behavior?
- Is this still a bug? (which is confusing as answer states that this should be fixed in iOS 6, but I encounter this problem in iOS 12)
(tested on XCode 10.1 beta 3 and XCode 10.0)