Memory issue in using UIImagePNGRepresentation

时光毁灭记忆、已成空白 提交于 2019-12-18 08:55:30

问题


Hi Guys I found this module to be troublesome. I import more than 100 images from Photolibrary, save them in documents directory with a different name. As expected I had a memory issue in the unusual place. It seems UIImagePNGRepresenation is caching files. So when I run the below process for 300+ images, I see "Overall bytes" in the range of 3.00 GB and crashes due to Memory (tested in allocations tool). I have pasted the code below. Is there any alternative for this code

-(void)something
{
   NSData *data=nil;
   for (int i=0; i<numberOfImages; i++) {

    @autoreleasepool {

        UIImage *image=[UIImage imageNamed:[NSString stringWithFormat:@"image%d.png",i]];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

        NSString *documentsDirectory = [[paths objectAtIndex:0] stringByAppendingString:@"directoryname"];

        NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"image%d.png",i]];

        //convert image into .png format
        data=UIImagePNGRepresentation(image);
        [data writeToURL:[NSURL URLWithString:fullPath] atomically:NO];
      }
   }
   data=nil;
}

回答1:


I solve this issue by sending a 4 channels image (RGBA or RGBX) instead of a 3 channels image (RGB).

You can check if there's any chance to change parameters of your image.




回答2:


The caching is coming from [UIImage imageNamed:], not UIImagePNGRepresentation(). Do this instead:

NSString *imageName = [NSString stringWithFormat:@"image%d.png", i];
NSString *imagePath = [[NSBundle mainBundle] pathForResource:imageName];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];

...



回答3:


I mailed this issue to Apple and they asked me to introduce sleep cycles between every allocation. Add sleep before allocation.



来源:https://stackoverflow.com/questions/9062506/memory-issue-in-using-uiimagepngrepresentation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!