无法在 Swift 3.0 中将 CIImage 转换为 UIImage [英] Unable to convert CIImage to UIImage in Swift 3.0

查看:19
本文介绍了无法在 Swift 3.0 中将 CIImage 转换为 UIImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码制作图像形式QR Code:

I am making image form QR Code by using following code:

  func createQRFromString(str: String) -> CIImage? {
        let stringData = str.dataUsingEncoding(NSUTF8StringEncoding)

        let filter = CIFilter(name: "CIQRCodeGenerator")

        filter?.setValue(stringData, forKey: "inputMessage")

        filter?.setValue("H", forKey: "inputCorrectionLevel")

        return filter?.outputImage
    }

然后我添加到 UIImageView 就像这样:

And Then I am adding to UIImageView Like this:

    if let img = createQRFromString(strQRData) {
        let somImage = UIImage(CIImage: img, scale: 1.0, orientation: UIImageOrientation.Down)
        imgviewQRcode.image = somImage
    }

现在我需要将其保存到 JPEGPNG 文件中.但是当我这样做时,我的应用程序崩溃了:

Now I need to save this to a JPEG or PNG file. But when I am doing so my app crashes:

    @IBAction func btnSave(sender: AnyObject) {

    //        // Define the specific path, image name
    let documentsDirectoryURL = try! NSFileManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
    // create a name for your image
    let fileURL = documentsDirectoryURL.URLByAppendingPathComponent("image.jpg")

    if let image = imgviewQRcode.image // imgviewQRcode is UIImageView
    {

        if let path = fileURL?.path
        {
            if !NSFileManager.defaultManager().fileExistsAtPath(fileURL!.path!)
            {
                if UIImageJPEGRepresentation(image, 1.0)!.writeToFile(path, atomically: true)
                {
                    print("file saved")
                }

            }//Checking existing file

        }//Checking path

    }//CHecking image

}

崩溃点

  UIImageJPEGRepresentation(image, 1.0)!.writeToFile(path, atomically: true)

原因

fatal error: unexpectedly found nil while unwrapping an Optional value

调试测试:

推荐答案

func convert(cmage:CIImage) -> UIImage
{       
    let context:CIContext = CIContext.init(options: nil)
    let cgImage:CGImage = context.createCGImage(cmage, from: cmage.extent)!        
    let image:UIImage = UIImage.init(cgImage: cgImage)        
    return image
}

使用此函数将 CIImage 转换为 UIImage .它有效.

Use this function to convert CIImage to UIImage . It works .

这篇关于无法在 Swift 3.0 中将 CIImage 转换为 UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆