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
解決方法
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
Author And Source
この問題について(CIImageをData型に変換したときにハマった時の対処法(Swift3.0)), 我々は、より多くの情報をここで見つけました https://qiita.com/coffeemk2/items/5f6f5352f9b8b1b02ec9著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .