如何在运行时正确压缩UIImages [英] How To Properly Compress UIImages At Runtime
问题描述
我需要加载4张图片进行同步编辑。当我从用户库加载它们时,内存超过500mb并崩溃。
I need to load 4 images for simultaneous editing. When I load them from the users library, the memory exceeds 500mb and crashes.
在我进行任何压缩尝试之前,这是来自原始分配转储的日志:
Here is a log from a raw allocations dump before I did any compression attempts:
代码:
var pickedImage = UIImage(data: imageData)
工具:
我已经阅读了几篇关于压缩UIImages的帖子。我试过减少UIImage:
I have read several posts on compressing UIImages. I have tried reducing the UIImage:
新代码:
var pickedImage = UIImage(data: imageData, scale:0.1)
乐器:
减少UIImage的比例没有影响?!非常奇怪。
Reducing the scale of the UIImage had NO EFFECT?! Very odd.
所以现在我尝试基于完整的UIImage创建JPEG压缩
So now I tried creating a JPEG compression based on the full UIImage
新代码:
var pickedImage = UIImage(data: imageData)
var compressedData:NSData = UIImageJPEGRepresentation(pickedImage,0)
var compressedImage:UIImage = UIImage(data: compressedData)!//this is now used to display
工具:
现在,我怀疑是因为我正在转换它仍在加载的图像。由于这一切都发生在来自PHImageManager的回调中,我需要一种方法从NSData创建一个压缩的UIImage,但是将比例设置为0.1没有做到。
Now, I suspect because I am converting the image its still being loaded. And since this is all occuring inside a callback from PHImageManager, I need a way to create a compressed UIImage from the NSData, but the setting the scale to 0.1 did NOTHING.
所以关于如何从NSData压缩这个UIImage的任何建议都会挽救生命!!!
So any suggestions as to how I can compress this UIImage right from the NSData would be life saving!!!
谢谢
推荐答案
在处理图像之前,我最终硬编码了尺寸缩小。下面是代码:
I ended up hard coding a size reduction before processing the image. Here is the code:
PHImageManager.defaultManager().requestImageForAsset(asset, targetSize:CGSizeMake(CGFloat(asset.pixelWidth), CGFloat(asset.pixelHeight)), contentMode: .AspectFill, options: options)
{
result, info in
var minRatio:CGFloat = 1
//Reduce file size so take 1/2 UIScreen.mainScreen().bounds.width/2 || CGFloat(asset.pixelHeight) > UIScreen.mainScreen().bounds.height/2)
{
minRatio = min((UIScreen.mainScreen().bounds.width/2)/(CGFloat(asset.pixelWidth)), ((UIScreen.mainScreen().bounds.height/2)/CGFloat(asset.pixelHeight)))
}
var size:CGSize = CGSizeMake((CGFloat(asset.pixelWidth)*minRatio),(CGFloat(asset.pixelHeight)*minRatio))
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
result.drawInRect(CGRectMake(0, 0, size.width, size.height))
var final = UIGraphicsGetImageFromCurrentImageContext()
var image = iImage(uiimage: final)
}
这篇关于如何在运行时正确压缩UIImages的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!