Idk 为什么我的图像在缓存中占用的大小比原始大小要大。我为此目的使用 alamofireImage 库,而我的应用程序用于 tvOS。这是我的代码。
let photoCache = AutoPurgingImageCache(
memoryCapacity: 100 * 1024 * 1024,
preferredMemoryUsageAfterPurge: 60 * 1024 * 1024
)
Alamofire.request(.GET, request, headers: headers)
.responseJSON { response in
if let JSON = response.result.value {
self.imagesArray = JSON["results"] as! NSMutableArray
for result in self.imagesArray{
self.getNetworkImage(result["url"] as! String, completion: { (UIImage) in
})}}}
func getNetworkImage(urlString: String, completion: (UIImage -> Void)) -> (Request) {
return Alamofire.request(.GET, urlString, headers: headers).responseImage { (response) -> Void in
guard let image = response.result.value else { return }
completion(image)
if response.response?.statusCode == 200{
self.cacheImage(image, urlString: urlString)
self.cachedImagesOnly.addObject(urlString)
}
if self.counter == 4{
self.activityIndicatorView.stopAnimating()
self.activityIndicatorView.hidden = true
var downloadedImage = UIImage()
let dicr = self.cachedImagesOnly.firstObject
let urlStringFetch = dicr!["url"] as! String
print("Fetching url: \(urlStringFetch)")
downloadedImage = self.cachedImage(urlStringFetch)!
print("Size of image from cache: \(downloadedImage.size)")
self.ssImage.image = downloadedImage
})
}
}
}
func cacheImage(image: Image, urlString: String) {
print("Total Cache memory size: \(self.photoCache.memoryCapacity)")
self.counter += 1
let jpgImageData = UIImageJPEGRepresentation(image, 1.0)
print("Image size before cache : \(jpgImageData?.length)")
self.cachedImagesOnly.addObject(urlString)
let URLRequest = NSURLRequest(URL: NSURL(string: "\(urlString)")!)
self.photoCache.addImage(UIImage(data: jpgImageData!)!, forRequest: URLRequest)
print("Cache memory usage after image cache: \(self.photoCache.memoryUsage)")
}
日志结果:
Total Cache memory size: 104857600
Image size: (1752.0, 1896.0) and string as identifier: http://image.com/9493.jpg
Image size before cache : Optional(1738247)
Cache memory usage after image cache: 13287168
Total Cache memory size: 104857600
Image size: (2875.0, 3872.0) and string as identifier: http://image.com/5025.jpg
Image size before cache : Optional(7049508)
Cache memory usage after image cache: 57815168
Total Cache memory size: 104857600
Image size: (2394.0, 3866.0) and string as identifier: http://image.com/169215.jpg
Image size before cache : Optional(6049349)
Cache memory usage after image cache: 94835984
Total Cache memory size: 104857600
Image size: (3811.0, 3049.0) and string as identifier: http://image.com/786.jpg
Image size before cache : Optional(2848557)
Cache memory usage after image cache: 46478956
所以,我在 GitHub 上读到他们在缓存内存已满时使用 FIFO,所以除了删除第一个对象之外,它会根据计算删除两个或三个。此外,仅考虑第一个日志结果,图像大小为 1738247 和 IDK,这增加了多少开销,缓存后使用大小变为 13287168,这几乎是 13 倍,非常奇怪。如果有人遇到过这个问题或可以识别我的错误,将不胜感激。提前致谢。