PHAsset到UIImage

dch*_*eng 53 swift phasset

我正在尝试从PHAsset创建一个UIImage(如缩略图或其他东西),以便我可以将它传递给需要UIImage的东西.我已经尝试调整我在SO上找到的解决方案(因为他们都直接将它传递到tableview或其他东西),但我没有成功(可能是因为我做得不对).

func getAssetThumbnail(asset: PHAsset) -> UIImage {
    var retimage = UIImage()
    println(retimage)
    let manager = PHImageManager.defaultManager()
    manager.requestImageForAsset(asset, targetSize: CGSize(width: 100.0, height: 100.0), contentMode: .AspectFit, options: nil, resultHandler: {(result, info)->Void in
            retimage = result
    })
    println(retimage)
    return retimage
}
Run Code Online (Sandbox Code Playgroud)

printlns告诉我,manager.request行现在没有做任何事情.如何让它作为UIImage给我资产.

谢谢.

dch*_*eng 82

这就是我需要它做的事情,万一有人也需要它.

func getAssetThumbnail(asset: PHAsset) -> UIImage {
    let manager = PHImageManager.defaultManager()
    let option = PHImageRequestOptions()
    var thumbnail = UIImage()
    option.synchronous = true
    manager.requestImageForAsset(asset, targetSize: CGSize(width: 100.0, height: 100.0), contentMode: .AspectFit, options: option, resultHandler: {(result, info)->Void in
            thumbnail = result!
    })
    return thumbnail
}
Run Code Online (Sandbox Code Playgroud)

编辑:Swift 3更新

func getAssetThumbnail(asset: PHAsset) -> UIImage {
    let manager = PHImageManager.default()
    let option = PHImageRequestOptions()
    var thumbnail = UIImage()
    option.isSynchronous = true
    manager.requestImage(for: asset, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFit, options: option, resultHandler: {(result, info)->Void in
        thumbnail = result!
    })
    return thumbnail
}
Run Code Online (Sandbox Code Playgroud)

  • 您可以通过settin PHImageManagerMaximumSize为targetSize获取原始图像. (6认同)
  • 你如何获得PHAsset的原始宽度+高度? (4认同)

Pat*_*gar 24

试试这个对我有用,希望它对你有帮助,

func getUIImage(asset: PHAsset) -> UIImage? {

    var img: UIImage?
    let manager = PHImageManager.default()
    let options = PHImageRequestOptions()
    options.version = .original
    options.isSynchronous = true
    manager.requestImageData(for: asset, options: options) { data, _, _, _ in

        if let data = data {
            img = UIImage(data: data)
        }
    }
    return img
}
Run Code Online (Sandbox Code Playgroud)


小智 9

雨燕5

extension PHAsset {
func getAssetThumbnail() -> UIImage {
    let manager = PHImageManager.default()
    let option = PHImageRequestOptions()
    var thumbnail = UIImage()
    option.isSynchronous = true
    manager.requestImage(for: self,
                         targetSize: CGSize(width: self.pixelWidth, height: self.pixelHeight),
                         contentMode: .aspectFit,
                         options: option,
                         resultHandler: {(result, info) -> Void in
                            thumbnail = result!
                         })
    return thumbnail
    }
}
Run Code Online (Sandbox Code Playgroud)


ZAF*_*007 8

简单的解决方案(Swift 4.2)

方法1:

extension PHAsset {

    var image : UIImage {
        var thumbnail = UIImage()
        let imageManager = PHCachingImageManager()
        imageManager.requestImage(for: self, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFit, options: nil, resultHandler: { image, _ in
            thumbnail = image!
        })
        return thumbnail
    }
}                          

let image = asset.image 
Run Code Online (Sandbox Code Playgroud)

如果您只需要UIImage,请使用此方法PHAsset.

要么

extension PHAsset {
    func image(targetSize: CGSize, contentMode: PHImageContentMode, options: PHImageRequestOptions?) -> UIImage {
        var thumbnail = UIImage()
        let imageManager = PHCachingImageManager()
        imageManager.requestImage(for: self, targetSize: targetSize, contentMode: contentMode, options: options, resultHandler: { image, _ in
            thumbnail = image!
        })
        return thumbnail
    }
}

let image = asset.image(targetSize: CGSize, contentMode: PHImageContentMode, options: PHImageRequestOptions?)
Run Code Online (Sandbox Code Playgroud)

使用此方法为您所需UIImage.

要么

extension PHAsset {

    func image(completionHandler: @escaping (UIImage) -> ()){
        var thumbnail = UIImage()
        let imageManager = PHCachingImageManager()
        imageManager.requestImage(for: self, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFit, options: nil, resultHandler: { img, _ in
            thumbnail = img!
        })
        completionHandler(thumbnail)
    }
}

let image = asset.image(completionHandler: {(img) in
    print("Finished")
})
Run Code Online (Sandbox Code Playgroud)

完成后使用此方法进行通知.

方法2:

extension PHAsset {
    var data : (UIImage, [AnyHashable : Any]) {
        var img = UIImage(); var information = [AnyHashable : Any](); let imageManager = PHCachingImageManager()
        imageManager.requestImage(for: self, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFit, options: nil, resultHandler: { image,info in
            img = image!
            information = info!
        })
        return (img,information)
    }
} 


let image_withData : (UIImage, [AnyHashable : Any]) = asset.data
Run Code Online (Sandbox Code Playgroud)

如果您想要UIImage和结果信息,请使用此方法PHAsset

要么

extension PHAsset {

    func data(targetSize: CGSize, contentMode: PHImageContentMode, options: PHImageRequestOptions?) -> (UIImage, [AnyHashable : Any]) {
        var img = UIImage(); var information = [AnyHashable : Any](); let imageManager = PHCachingImageManager()
        imageManager.requestImage(for: self, targetSize: targetSize, contentMode: contentMode, options: options, resultHandler: { image,info in
            img = image!
            information = info!
        })
        return (img,information)
    }
}

let data = asset?.data(targetSize: CGSize, contentMode: PHImageContentMode, options: PHImageRequestOptions?)
Run Code Online (Sandbox Code Playgroud)

将此方法用于所需的数据.


Oha*_*adM 7

我建议使用Apple的PHCachingImageManager(继承自PHImageManager):

PHCachingImageManager对象为照片或视频资产提取或生成图像数据

此外,PHCachingImageManager支持更好的缓存机制.

获取同步缩略图的示例:

let options = PHImageRequestOptions()
options.deliveryMode = .HighQualityFormat
options.synchronous = true // Set it to false for async callback

let imageManager = PHCachingImageManager()
imageManager.requestImageForAsset(YourPHAssetVar,
                                  targetSize: CGSizeMake(CGFloat(160), CGFloat(160)),
                                  contentMode: .AspectFill,
                                  options: options,
                                  resultHandler: { (resultThumbnail : UIImage?, info : [NSObject : AnyObject]?) in

                                                   // Assign your thumbnail which is the *resultThumbnail*
                                                  }
Run Code Online (Sandbox Code Playgroud)

此外,您可以使用PHCachingImageManager 缓存图像以获得更快的UI响应:

要使用缓存图像管理器:

  1. 创建PHCachingImageManager实例.(此步骤使用共享的PHImageManager实例替换.)

  2. 使用PHAsset类方法来获取您感兴趣的资产.

  3. 要为这些资源准备图像,请调用startCachingImagesForAssets:targetSize:contentMode:options:方法,其中包含目标大小,内容模式以及计划在以后为每个资产请求图像时使用的选项.

  4. 当您需要单个资产的图像时,请调用requestImageForAsset:targetSize:contentMode:options:resultHandler:method,并传递您在准备该资产时使用的相同参数.

如果您请求的图像是已经准备好的图像,则PHCachingImageManager对象会立即返回该图像.否则,照片会根据需要准备图像并将其缓存以供以后使用.

在我们的例子中:

var phAssetArray : [PHAsset] = []

for i in 0..<assets.count
{
  phAssetArray.append(assets[i] as! PHAsset)
}

let options = PHImageRequestOptions()
options.deliveryMode = .Opportunistic
options.synchronous = false

self.imageManager.startCachingImagesForAssets(phAssetArray,
                                              targetSize: CGSizeMake(CGFloat(160), CGFloat(160)),
                                              contentMode: .AspectFill,
                                              options: options)
Run Code Online (Sandbox Code Playgroud)


Sou*_*ean 7

对于Swift 3.0.1:

func getAssetThumbnail(asset: PHAsset, size: CGFloat) -> UIImage {
    let retinaScale = UIScreen.main.scale
    let retinaSquare = CGSize(width: size * retinaScale, height: size * retinaScale)//(size * retinaScale, size * retinaScale)
    let cropSizeLength = min(asset.pixelWidth, asset.pixelHeight)
    let square = CGRect(x:0, y: 0,width: CGFloat(cropSizeLength),height: CGFloat(cropSizeLength))
    let cropRect = square.applying(CGAffineTransform(scaleX: 1.0/CGFloat(asset.pixelWidth), y: 1.0/CGFloat(asset.pixelHeight)))

    let manager = PHImageManager.default()
    let options = PHImageRequestOptions()
    var thumbnail = UIImage()

    options.isSynchronous = true
    options.deliveryMode = .highQualityFormat
    options.resizeMode = .exact
    options.normalizedCropRect = cropRect

    manager.requestImage(for: asset, targetSize: retinaSquare, contentMode: .aspectFit, options: options, resultHandler: {(result, info)->Void in
        thumbnail = result!
    })
    return thumbnail
}
Run Code Online (Sandbox Code Playgroud)

资源:https://gist.github.com/lvterry/f062cf9ae13bca76b0c6#file-getassetthumbnail-swift


Tho*_*aul 6

斯威夫特4。

resizeModedeliveryMode-这些可以根据用户要求进行设置。

isNetworkAccessAllowed -将其设置为“ true”以从云中获取图像

imageSize-所需的图像尺寸

func getImageFromAsset(asset:PHAsset,imageSize:CGSize, callback:@escaping (_ result:UIImage) -> Void) -> Void{

    let requestOptions = PHImageRequestOptions()
    requestOptions.resizeMode = PHImageRequestOptionsResizeMode.fast
    requestOptions.deliveryMode = PHImageRequestOptionsDeliveryMode.highQualityFormat
    requestOptions.isNetworkAccessAllowed = true
    requestOptions.isSynchronous = true
    PHImageManager.default().requestImage(for: asset, targetSize: imageSize, contentMode: PHImageContentMode.default, options: requestOptions, resultHandler: { (currentImage, info) in
        callback(currentImage!)
    })
}
Run Code Online (Sandbox Code Playgroud)