CIImageをData型に変換したときにハマった時の対処法(Swift3.0)


iOSでCoreImageを用いてQRコードを生成し, 生成したQRコードをOpenURLで別アプリに送ろうとした際にData型に変換しようとした時にハマったのでメモ

状況

before.swift
import UIKit
import CoreImage

// String から QRコードを作成(CIImage)
let str = "Hello, playground"
guard let strData = str.data(using: String.Encoding.utf8) else { fatalError() }
let sizeTransform = CGAffineTransform(scaleX: 10, y: 10)
let params:[String:Any] = ["inputMessage":strData,"inputCorrectionLevel":"M"]
let ciImage = CIFilter(name: "CIQRCodeGenerator", withInputParameters: params)?.outputImage?.applying(sizeTransform)
guard let ciImage = ciImage else { fatalError() }


// CIImage -> UIImage -> Data
let uiImage = UIImage(ciImage: ciImage)
let imageData = UIImagePNGRepresentation(uiImage) // nil

解決方法

CIImageを一度CGImageに変換し,UIImageに変換してData型にすれば良いようです

after.swift
import UIKit
import CoreImage

// String から QRコードを作成(CIImage)
let str = "Hello, playground"
guard let strData = str.data(using: String.Encoding.utf8) else { fatalError() }
let sizeTransform = CGAffineTransform(scaleX: 10, y: 10)
let params:[String:Any] = ["inputMessage":strData,"inputCorrectionLevel":"M"]
let ciImage = CIFilter(name: "CIQRCodeGenerator", withInputParameters: params)?.outputImage?.applying(sizeTransform)
guard let ciImage = ciImage else { fatalError() }


// CIImage -> CGImage -> UIImage -> Data 
let context = CIContext()
let cgImage = context.createCGImage(ciImage, from: ciImage.extent)
let uiImage = UIImage(cgImage: cgImage!)
let imageData = UIImagePNGRepresentation(uiImage) // 6120 bytes