我正在尝试将UIImage转换为PHAsset,但没有找到任何解决方案。我发现的只是反之亦然(即PHAsset到UIImage)。
场景是,我将从自定义目录中获取图像到PHAssetCollection中,并在UICollectionView中显示。我也想包括更多的图片,这里从以前的屏幕,是来自远程来源。我不想将远程图像保存到我的目录中,而是希望将它们包含在我的UICollectionView中。
请建议我的解决方案或一些好的替代方案,以便UICollectionView的来源是相同的(即PHAssetCollection)。
发布于 2016-05-05 07:14:55
您不希望将PHAsset转换为UIImage。我不知道这是否可能,应该是不可能的,因为PHAsset和UIImage有不同的属性、行为等等。反之亦然,因为UIImage的所有属性都可以从PHAsset派生出来,反之亦然。
相反,将集合视图的数据源更改为[UIImage],而将PHAsset转换为UIImage。这种方法是干净的,并解决了您必须将UIImage转换为PHImage的另一个问题。
发布于 2018-07-12 15:39:49
晚会有点晚了,但我会为未来的人发我的答案。
我在我的应用程序中所做的就是截图,并将其保存到Photos应用程序的专用相册中。
下面的示例中的getAlbum()只是检索相册的助手方法。
ImageStoreItem只是一个带有两个字段的包装器:image: UIImage和id: String作为原始PHAsset的标识符。
/**
Saves the image to the album in the Photos app.
- Throws:
- `ImageStore.TypeError.accessDenied`
if the user has denied access to the photo library.
- An error thrown by `PHPhotoLibrary`.
*/
func saveImage(_ image: UIImage) throws {
let album = try getAlbum()
try PHPhotoLibrary.shared().performChangesAndWait {
let imgReq = PHAssetChangeRequest.creationRequestForAsset(from: image),
albReq = PHAssetCollectionChangeRequest(for: album)!
albReq.addAssets([imgReq.placeholderForCreatedAsset] as NSFastEnumeration)
}
}
/**
Fetches images in the app album.
- Throws:
- `ImageStore.TypeError.accessDenied`
if the user has denied access to the photo library.
- An error thrown by `PHPhotoLibrary`.
- `NSError` thrown by `PHImageManager`
if fetching images from the `PHAsset` list failed.
- `Globalerror.unknown` if no image was fetched,
but there is no corresponding error object.
- Returns:
An array of `ImageStoreItem`s with the album items.
*/
func getImages() throws -> [ImageStoreItem] {
let album = try ImageStore.shared.getAlbum(),
assets = PHAsset.fetchAssets(in: album, options: nil)
let size = UIScreen.main.bounds.size,
opt = PHImageRequestOptions()
opt.isSynchronous = true
var res = [ImageStoreItem]()
var err: Error? = nil
let handler: (PHAsset) -> (UIImage?, [AnyHashable : Any]?) -> Void =
{ (asset) in
{ (image, info) in
if let image = image {
let item = ImageStoreItem(image: image,
id: asset.localIdentifier)
res.append(item)
} else if let info = info {
if let error = info[PHImageErrorKey] {
err = error as! NSError
} else {
var userInfo = [String : Any]()
for (key, value) in info {
userInfo[String(describing: key)] = value
}
err = GlobalError.unknown(info: userInfo)
}
}
}
}
assets.enumerateObjects { (asset, _, _) in
PHImageManager.default()
.requestImage(for: asset,
targetSize: size,
contentMode: .default,
options: opt,
resultHandler: handler(asset))
}
if let error = err { throw error }
return res
}关于PhotoKit的文档不太令人印象深刻,但是到处看看,你就会知道它的诀窍了。
https://stackoverflow.com/questions/37043933
复制相似问题