-1

I made a method to resize an image. When it resizes an image in images array, it become too much memories(e.g. 200MB~300MB) especially when an image is a High-Quality image(iPhone6/6s). My Project is in ARC. If I want to make it, how do I have to code it? Please teach me how to "immediately" or "forced" release "trimmedImage" instance.

I find this by Instruments(CGImage eats much memory). I tried to use @autoreleasepool, trimmedImage = nil; and [trimmedImage release];, but they also work bad(not released trimmedImage memory).

+ (void)cropImages: (NSArray *)images {
    for (__weak UIImage *image in images) {
        UIImage *resizedImage = [self cropRectImage:image];
    }
}


+ (UIImage *)cropRectImage: (UIImage *)image {
    float w = image.size.width;
    float h = image.size.height;
    CGRect rect;

    if (h <= w) {
        float x = w / 2 - h / 2;
        float y = 0;
        rect = CGRectMake(x, y, h, h);
    }else {
        float x = 0;
        float y = h / 2 - w / 2;
        rect = CGRectMake(x, y, w, w);
    }

    CGImageRef cgImage = CGImageCreateWithImageInRect(image.CGImage, rect);
    UIImage *trimmedImage = [UIImage imageWithCGImage:cgImage];

    CGSize newSize = CGSizeMake(320, 320);
    UIGraphicsBeginImageContext(newSize);
    UIImage *resizedImage = nil;
    [trimmedImage drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    // TODO: ここでAutoReleaseされるはずだが... (http://vladimir.zardina.org/2010/05/resizing-uiimage-objects/)
    resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    image = nil;
    cgImage = nil;

    return resizedImage;
}
masuhara
  • 179
  • 1
  • 2
  • 9

1 Answers1

2

You have a bad memory leak in your cropRectImage: method. You never release cgImage.

Replace this line:

cgImage = nil;

with:

CGImageRelease(cgImage);

ARC doesn't work with any of the C functions and related references.

I also suggest you run Analyze on your project. In Xcode, go to Project and then Analyze.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Thank you very much! It's very important. I replace my code(cgImage = nil) with your code(CGImageRelease). But it doesn't reduce my app's memory. UIImage{ 3000, 2002 } for - sentence roop 1 → 98.9 MB roop 2 → 148.1 MB roop 3 → 171.4 MB ... roop 6 → 280 MB(sometime crash) Does CGImageRelease release its memory immediately? I want to reduce it. Do you have other any good ideas? – masuhara Dec 13 '15 at 02:52