27
17

More than 3 years have passed since last update.

[Swift]UIImage型とData型の相互変換

Last updated at Posted at 2020-06-15

はじめに

Swift4からUIImage型とData型の変換をシンプルに書けるようになったので紹介します。
特にUIImage型→Data型への変換はしばしばextensionを作っていましたが、それらと同じことが公式にできるようになりました。

UIImage型→Data型

imageをData型に変換したいUIImage型のインスタンスとします

// pngに変換する
image.pngData()

// jpegに変換する
// compressionQualityには0~1の範囲で圧縮率を指定する
image.jpegData(compressionQuality: 1)

Data型→UIImage型

dataをData型に変換したいUIImage型のインスタンスとします

// UIImage?型になるので、必要に応じてアンラップをする必要がある
UIImage(data: data)

// 強制アンラップしてUIImage型にする
UIImage(data: data)!

参考リンク

https://developer.apple.com/documentation/uikit/uiimage/1624096-pngdata
https://developer.apple.com/documentation/uikit/uiimage/1624115-jpegdata
https://developer.apple.com/documentation/uikit/uiimage/1624106-init

27
17
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
27
17