Edited at

UIImagePickerControllerで取得した画像の形式を取得する

More than 1 year has passed since last update.

(NS)Dataに変換する時に以下の2種類あるのでその判定用。

UIImageJPEGRepresentation

UIImagePNGRepresentation

enum ImageType: String {

case jpg = "JPG"
case png = "PNG"
case gif = "GIF"
}

extension SomeViewController: UIImagePickerControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) {
var imageType: ImageType?
if picker.sourceType == .camera {
// カメラはjpg固定
imageType = .jpg
} else {
// ファイルの格納先の拡張子から形式を取得する
if let url = info[UIImagePickerControllerReferenceURL] as? URL, let component = URLComponents(url: url, resolvingAgainstBaseURL: false) {
if let queryItems = component.queryItems {
for query in queryItems {
if let value = query.value, query.name == "ext" {
imageType = ImageType(rawValue: value)
}
}
}
}
}

guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else { return }

// some action
}
}