从PHAsset视频中提取UIImage



我试图在swift中获得视频的预览图像。我有PHAsset,需要将它的预览图像转换为UIImage

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

我建议你检查"选项"区域,这样你就可以以最适合你的方式获得资产。

跟随下一个代码:

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)
}
}
}
}

希望你觉得有用~

最新更新