0
1

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 3 years have passed since last update.

【Swift】カメラロールから取得した動画サムネイルの画質が悪い時・向きがおかしい時

Posted at

環境

Swift5
Xcode11.6

起こったこと

カメラロールから動画を選択する画面の実装をしていた時。
動画のプレビュー画像の画質がなぜか荒い。

リソースの取得はPHImageManagerで行っていた。

見直すべき点その1

リソースの取得時に画質の設定を行う。
ググると一番よく出てくる対策。

let phImageManager = PHImageManager()
let assets = PHAsset.fetchAssets(with: .video, options: nil)

// クオリティを指定する
let options = PHVideoRequestOptions()
options.deliveryMode = .highQualityFormat

assets.enumerateObjects({ obj, index, stop in
    phImageManager.requestPlayerItem(
        forVideo: assets[index],
        options: options,  // 設定を与える
        resultHandler: { playerItem, info in
            ...
        })
})
                

自分の場合はこれが原因ではなかった。

見直すべき点その2

動画からブレビュー画像を生成時に画質が落ちていないか?


let item: AVPlayerItem = ... // その1でPHImageManagerを利用して取得したもの
let asset:AVAsset = item.asset
let gene = AVAssetImageGenerator(asset:asset)
gene.appliesPreferredTrackTransform = true
gene.maximumSize = CGSize(width: ..., height: ...) // これが原因だった!
let capImg = try! gene.copyCGImage(at: CMTime.zero, actualTime: nil)

gene.maximumSizeで指定したサイズが小さかった(実際に表示するビューと同じ大きさにしていた)のが原因でした。
この一行を取り除くと見事、綺麗な画質のプレビューが取得できました〜

プレビュー画像の向きがおかしい時

gene.appliesPreferredTrackTransform = true

の一行を忘れないように!

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?