AppSeedのアプリ開発ブログ

アプリ開発会社AppSeed(アップシード)開発担当のブログです。iOS、Android、Unity、Cocos2d-xなどアプリ開発関連のTipsや備忘録、アプリ開発に役立つ情報を発信します。

iOSでアプリ内部(Document)に画像(UIImage)を保存する方法【iOSアプリ開発】

iOSでアプリ内部に画像を保存する方法に関するメモ。

Documentsディレクトリに保存する場合は以下の方法でできます。


iOSでアプリ内部に画像を保存する方法

//画像保存
    // DocumentディレクトリのfileURLを取得
    func getDocumentsURL() -> NSURL {
        let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as NSURL
        return documentsURL
    }
    // ディレクトリのパスにファイル名をつなげてファイルのフルパスを作る
    func fileInDocumentsDirectory(filename: String) -> String {
        let fileURL = getDocumentsURL().appendingPathComponent(filename)
        return fileURL!.path
    }
    //画像を保存するメソッド
    func saveImage (image: UIImage, path: String ) -> Bool {
        let jpgImageData = image.jpegData(compressionQuality:0.5)
        do {
            try jpgImageData!.write(to: URL(fileURLWithPath: path), options: .atomic)
        } catch {
            print(error)
            return false
        }
        return true
    }


使い方としてはこんな感じ↓

saveImage(image: "UIImage", path: "ファイル名")

DocumentディレクトリのURL取得


DocumentディレクトリのURLは「 FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] 」で取得。

Apple Developer Documentation


UIImageの保存

画像の保存は、UIImageをDataクラスに変換して、「write(to url: URL, options: Data.WritingOptions = default) throws」で保存してます。

Apple Developer Documentation


UIImageをjpegデータに変換

iPhoneのカメラロールから取得したUIImageをそのまま保存するとデータサイズが大きくなってしまうので、

UIImageのjpegDataでjpeg画像に変換してから保存してます。

Apple Developer Documentation