12
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2016-11-07

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

12
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?