我有一个基于ARC的应用程序,该应用程序从Web服务中加载约2,000个相当大(1-4MB)的Base64编码图像。它将Base64解码的字符串转换为.png
图像文件,并将其保存到磁盘。所有这些都是在一个循环中完成的,在该循环中我应该没有任何缠绵的引用。
我分析了我的应用程序,发现UIImagePNGRepresentation占用了大约50%的可用内存。
我所看到的方式是,UIImagePNGRepresentation正在缓存其创建的图像。解决此问题的一种方法是刷新该缓存。有什么想法可以做到这一点吗?
另一个解决方案是使用除UIImagePNGRepresentation之外的其他东西?
我已经尝试过运气了:Memory issue in using UIImagePNGRepresentation。更不用说我不能真正使用那里提供的解决方案,因为它会使我的应用程序运行太慢。
这是我从循环中调用的方法。 UIImage是从Base64转换的图像:
+ (void)saveImage:(UIImage*)image:(NSString*)imageName:(NSString*)directory {
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *pathToFolder = [documentsDirectory stringByAppendingPathComponent:directory];
if (![fileManager fileExistsAtPath:pathToFolder]) {
if(![fileManager createDirectoryAtPath:pathToFolder withIntermediateDirectories:YES attributes:nil error:NULL]) {
// Error handling removed for brevity
}
}
NSString *fullPath = [pathToFolder stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]]; //add our image to the path
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)
// clear memory (this did nothing to improve memory management)
imageData = nil;
fileManager = nil;
}
编辑:
图像尺寸从1000 * 800到3000 * 2000不等。
最佳答案
您可以通过自动释放池包装方法主体
+ (void)saveImage:(UIImage*)image:(NSString*)imageName:(NSString*)directory {
@autoreleasepool
{
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *pathToFolder = [documentsDirectory stringByAppendingPathComponent:directory];
if (![fileManager fileExistsAtPath:pathToFolder]) {
if(![fileManager createDirectoryAtPath:pathToFolder withIntermediateDirectories:YES attributes:nil error:NULL]) {
// Error handling removed for brevity
}
}
NSString *fullPath = [pathToFolder stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]]; //add our image to the path
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)
}
}
但实际上,如果您向我们提供更多数字,可能会有所帮助:
图像有什么尺寸。这很重要,因为图像数据以原始像素存储在内存中。即图像
2000px width * 2000px height * 4 Bytes (RGBA) ~ 15MB
。现在想象一下,转换算法将必须存储每个像素或至少某些区域的信息。预计会有大量的人。