gpt4 book ai didi

ios - 如何将图片保存到自定义相册?

转载 作者:IT王子 更新时间:2023-10-29 05:05:31 27 4
gpt4 key购买 nike

我有一个全新的 iOS 应用程序,它可以生成图像并让用户将它们保存到 Camera SavedPhotosAlbum 中。但是,我想做一些类似 Snapchat 和 Frontback 的东西,并将这些图像也保存到自定义命名的相册中。

所以这是我现在的代码:

let imageToSave = self.currentPreviewImage

let softwareContext = CIContext(options:[kCIContextUseSoftwareRenderer: true])
let cgimg = softwareContext.createCGImage(imageToSave, fromRect:imageToSave.extent())

ALAssetsLibrary().writeImageToSavedPhotosAlbum(cgimg, metadata:imageToSave.properties(), completionBlock:nil)

我见过一些人在 Objective-C 中这样做的例子,但我无法将其转换为 Swift,而且我检查了 writeImageToSavedPhotosAlbum 方法签名,但它们似乎都不允许保存到自定义相册。

最佳答案

我想出了这个单例类来处理它:

import Photos

class CustomPhotoAlbum {

static let albumName = "Flashpod"
static let sharedInstance = CustomPhotoAlbum()

var assetCollection: PHAssetCollection!

init() {

func fetchAssetCollectionForAlbum() -> PHAssetCollection! {

let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", CustomPhotoAlbum.albumName)
let collection = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions)

if let firstObject: AnyObject = collection.firstObject {
return collection.firstObject as! PHAssetCollection
}

return nil
}

if let assetCollection = fetchAssetCollectionForAlbum() {
self.assetCollection = assetCollection
return
}

PHPhotoLibrary.sharedPhotoLibrary().performChanges({
PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(CustomPhotoAlbum.albumName)
}) { success, _ in
if success {
self.assetCollection = fetchAssetCollectionForAlbum()
}
}
}

func saveImage(image: UIImage) {

if assetCollection == nil {
return // If there was an error upstream, skip the save.
}

PHPhotoLibrary.sharedPhotoLibrary().performChanges({
let assetChangeRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(image)
let assetPlaceholder = assetChangeRequest.placeholderForCreatedAsset
let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.assetCollection)
albumChangeRequest.addAssets([assetPlaceholder])
}, completionHandler: nil)
}


}

当您第一次实例化该类时,如果自定义相册尚​​不存在,则会创建它。您可以像这样保存图像:

CustomPhotoAlbum.sharedInstance.saveImage(image)

注意:CustomPhotoAlbum 类假定该应用程序已具有访问照片库的权限。处理权限有点超出了这个问题/答案的范围。所以确保 PHPhotoLibrary.authorizationStatus() == .Authorize 在你使用它之前。并在必要时申请授权。

关于ios - 如何将图片保存到自定义相册?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28708846/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com