Swift - 如何使用AlamofireImage / ImageShack节省内存? [英] Swift - How to save memory using AlamofireImage/ImageShack?

查看:242
本文介绍了Swift - 如何使用AlamofireImage / ImageShack节省内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Alamofire AlamofireImage 来使用带有 Firebase 后端的 ImageShack 存储来缓存图片。有时内存超过100MB。我想学习如何在上传之前改进我的图像缓存和良好的缩放。例如,我使用 AutoPurgingImageCache 在类整个项目中声明了一个公共缓存:

I'm using Alamofire, AlamofireImage to cache images using ImageShack storage with Firebase backend. Sometimes memory comes over 100MB. I want to learn how to improve my image caching and well scaling before uploading. For example I have declared one common cache in class whole project using that AutoPurgingImageCache:

let photoCache = AutoPurgingImageCache(
        memoryCapacity: 100 * 1024 * 1024,
        preferredMemoryUsageAfterPurge: 60 * 1024 * 1024
    )

有没有办法定义这些 memoryCapacity preferredMemoryUsageAfterPurge 来节省内存?它们究竟是什么意思?

Is there any way to define these memoryCapacity, preferredMemoryUsageAfterPurge to save memory? What do they mean exactly?

我在 didFinishPickingImage 下使用 Alamofire.upload

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {

        let urlStr = "http://post.imageshack.us/upload_api.php"
        let url = NSURL(string: urlStr)!
        let imgData = UIImageJPEGRepresentation(image, 0.25)!

        let keyData = "____IMGSHACK_API_KEY_____".dataUsingEncoding(NSUTF8StringEncoding)!
        let keyJSON = "json".dataUsingEncoding(NSUTF8StringEncoding)!
        let publicData = "no".dataUsingEncoding(NSUTF8StringEncoding)!

        Alamofire.upload(.POST, url, headers: nil,
                         multipartFormData: { multipartFormData in
                            multipartFormData.appendBodyPart(data: imgData, name:"fileupload", fileName:"image", mimeType: "image/jpg")
                            multipartFormData.appendBodyPart(data: keyData, name: "key")
                            multipartFormData.appendBodyPart(data: keyJSON, name: "format")
                            multipartFormData.appendBodyPart(data: publicData, name: "public")
            }, encodingCompletion: { encodingResult in
                switch encodingResult {
                case .Success(let upload, _, _):
                    upload.validate()
                    upload.responseJSON { response in
                        let responseJSON = response.result.value as? [String: AnyObject]
                        if let links = responseJSON!["links"] as? Dictionary<String, AnyObject> {
                            if let imgLink = links["image_link"] as? String {
                                self.postToFirebase(imgLink)
                                print(imgLink)
                            }
                        }
                    }
                case .Failure(let encodingError):
                    print(encodingError)
                }
        })

        self.dismissViewControllerAnimated(true, completion: nil)
        self.tableView.contentOffset = CGPointMake(0, -60);

}

我认为 UIImageJPEGRepresentation(图片,0.25)! 不是很好的压缩情况,我的图片来自互联网的全尺寸。如果我在压缩之前进行缩放上传,例如:

I think UIImageJPEGRepresentation(image, 0.25)! is not well compression case, my images comes from internet as full size. If I scale before compression to upload like:

let size = CGSize(width: 500.0, height: 273.0)
let scaledImage = image.af_imageScaledToSize(size)

我认为网络平台的图像质量可能不好。所以我在图像下载后进行缩放和缓存:

I think web platform can be bad image quality. So I do scale and caching after image downloading:

    //MARK: - Image Downloading

    func getNetworkImage(urlString: String, comesFrom: String, completion: (UIImage -> Void)) -> (Request) {

        return Alamofire.request(.GET, urlString).responseImage { (response) -> Void in
            guard let image = response.result.value else { return }
            completion(image)

            if comesFrom == "collectionPage" {
                self.cacheCollectionImage(image, urlString: urlString)
            }
            else if comesFrom == "postPage" {
                self.cachePostImage(image, urlString: urlString)
            }

        }
    }

    //MARK: - Image Caching

    func cacheCollectionImage(image: Image, urlString: String) {

        let size = CGSize(width: 188.0, height: 120.0)
        let scaledImage = image.af_imageScaledToSize(size)

        photoCache.addImage(scaledImage, withIdentifier: urlString)

    }

    func cachePostImage(image: Image, urlString: String) {

        let size = CGSize(width: 300.0, height: 165.0)
        let scaledImage = image.af_imageScaledToSize(size)

        photoCache.addImage(scaledImage, withIdentifier: urlString)

    }


    func cachedImage(urlString: String) -> Image? {
        print("cachedImage() func ended")
        return photoCache.imageWithIdentifier(urlString)
    }

此外,我的应用程序打开,内存使用量为40MB 。而且我看到max 最高使用量130MB ,上传和滚动后返回 AutoPurgingImageCache 可以正常工作并减少使用内存,但我认为仍然如此。

Also my application opens with 40MB memory usage. And than I see max top usage 130MB, after uploads and scrolling to turn back AutoPurgingImageCache works and decreasing memory using but I think still so much.

你有什么建议我在这些条件下节省内存?我需要一些解释,你想用什么工具或策略来处理它,尽可能为每个平台提供良好的质量。

What do you advice me to save memory in these conditions? I need some explanations, what you want to say tools or strategy to handle it as possible as good quality for every platforms.

推荐答案

你只需要复制&粘贴来自AlamofireImage的代码:

You just have copy & pasted the code from AlamofireImage:

let photoCache = AutoPurgingImageCache(
    memoryCapacity: 100 * 1024 * 1024,
    preferredMemoryUsageAfterPurge: 60 * 1024 * 1024
)

1024字节x 1024字节x 100将创建一个100 MB的内存缓存。达到该限制后,缓存大小将减少到60 MB。如果你不是这么大的缓存,那么只需减少它。这里没有正确的数字,它完全取决于您的使用案例。我个人使用内存缓存20 MB和100 MB磁盘缓存。

1024 bytes x 1024 bytes x 100 will create a 100 MB in-memory cache. After that limit is reached the cache size will be reduced to 60 MB. If you do not wan't such a big cache then just reduce it. There is no "correct" number here, it depends solely on your use case. I, personally, use 20 MB in memory cache and 100 MB disk cache.

这篇关于Swift - 如何使用AlamofireImage / ImageShack节省内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆