从 PHAsset 视频中提取 UIImage

Extracting UIImage from PHAsset video

我正在尝试在 swift.I 中获取视频的预览图像有 PHAsset 并且需要将其预览图像转换为 UIImage

欢迎光临! , 要首先从视频中获取缩略图,您需要获取 PHAsset,然后使用 PHCachingImageManager() 以从您的视频中请求缩略图。

我会推荐你​​查看'options'区,这样你就可以以最适合你的方式获得资产。

遵循下一个代码:

let imageManager = PHCachingImageManager()
var allAssetsinAlbum: PHFetchResult<PHAsset>!
var assetsInAlbum = [UIImage]()

func getThumbnail(){
    let options = PHFetchOptions()
    options.predicate = NSPredicate(format: "title = %@", "YourAlbumName")// Get the assets
    let album = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: options)
    ///- Note: It 's also a good idea to check if the album is available, not doing it here
    let thumbnailSize = CGSize(width: 160, height: 160)// you can customize the size here
    allAssetsinAlbum = PHAsset.fetchAssets(in: album.firstObject!, options: nil) as PHFetchResult<PHAsset>
    let limit = allAssetsinAlbum.count
    if limit != 0 {
        for i in 0...limit-1 {
            let isVideo = allAssetsinAlbum.object(at: i).mediaType == .video ?  true : false /// Check if it is a VIDEO
            let options = PHImageRequestOptions()//Options: How the thumbnails are obtained
            options.isSynchronous = true
            options.isNetworkAccessAllowed = true //get those saved in iCloud
            options.deliveryMode = .fastFormat// fastest but the quality is not very good
            imageManager.requestImage(for: allAssetsinAlbum.object(at: i) , targetSize: thumbnailSize, contentMode: .default, options: options, resultHandler: { asset, _ in /// save video THUMBNAILS
                if isVideo{
                    assetsInAlbum.append(asset!)
                }
            })
        }
    }
}

那我猜你想把它显示在列表或其他东西中。

struct ContentView: View {
var body: some View {
    
    getThumbnail()
    let columns = [GridItem(.adaptive(minimum: 100, maximum: 100))]
    
    
    return LazyVGrid(columns: columns, spacing: 20 ) {
        ForEach(Array(assetsInAlbum.enumerated()), id:\.offset) { index, element in
            ZStack{
                Image(uiImage: element)
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(width: 80, height: 80)
                    .clipped()
                    .cornerRadius(5)
            }
        }
    }
}

希望对你有用!~