1
0

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 1 year has passed since last update.

カメラロールの写真をUIImageで上書き保存するミニマムなサンプル

Posted at

ライブラリの写真をPHAssetで取得して、UIImageで更新保存するサンプルです。
ググっても意外と出てこない模様なので。

ちゃんと読もう

Apple 公式のサンプル

環境

Xcode 13.0

ミニマムなサンプルコード

import UIKit
import Photos

private lazy var formatIdentifier = Bundle.main.bundleIdentifier!
private let formatVersion = "1.0"

private func update(asset: PHAsset, toPhoto: UIImage, completionHandler: @escaping ((Bool, Error?) -> Void)) {
    let options = PHContentEditingInputRequestOptions()
    options.canHandleAdjustmentData = { _ in
        return true
    }
    asset.requestContentEditingInput(with: options) { input, info in
        guard let input = input else { fatalError("Can't get the content-editing input: \(info)") }
        
        DispatchQueue.global(qos: .userInitiated).async {
            let output = PHContentEditingOutput(contentEditingInput: input)
            let adjustmentData = PHAdjustmentData(formatIdentifier:formatIdentifier, formatVersion:formatVersion, data: "my app".data(using: .utf8)!)
            output.adjustmentData = adjustmentData
            
            let jpg = toPhoto.jpegData(compressionQuality: 0.9)
            
            do {
                try jpg?.write(to: output.renderedContentURL)
            } catch let error {
                fatalError("Can't save image to PHContentEditingOutput.renderedContentURL : \(error).")
            }
            
            PHPhotoLibrary.shared().performChanges {
                let request = PHAssetChangeRequest(for: asset)
                request.contentEditingOutput = output
                
            } completionHandler: { success, error in
                completionHandler(success, error)
            }
        }
    }
}

なんとかしたい

  • renderedContentURLに吐き出せるのがなぜかjpg一択?
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?