1

I try to combine two UIImage with the following code:

- (void)combineImage:(UIImage *)image WithFrame:(CGRect)frame Completion:(ImageProcessorCompletionBlock)block {
    __weak typeof(self) wSelf = self;

    dispatch_async(_queue, ^{
        if (wSelf) {
            typeof(wSelf) sSelf = wSelf;

            UIGraphicsBeginImageContextWithOptions(sSelf.originalImage.size, NO, 0.0);

            [sSelf.originalImage drawInRect:CGRectMake(0, 0, sSelf.originalImage.size.width, sSelf.originalImage.size.height)];
            [image drawInRect:frame];

            UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();

            dispatch_async(dispatch_get_main_queue(), ^{
                if (block) {
                    block(result);
                }
            });
        }
    });
}

That works but when I check out the usage of memory, it scared me. Every time I run the method the memory rise up and never release. Sometimes I receive the memory warning. Can anyone tell me why and give me a solution to solve the problem? Thanks a lot!

Tony.Lee
  • 662
  • 1
  • 7
  • 14
  • 2
    Unrelated but your `if (block)` check should encompass the entire method body. No sense in doing any of the work if the caller doesn't care about the result. – rmaddy May 03 '17 at 15:43
  • May be your image is big in size? – iphonic May 03 '17 at 17:51
  • Images are big (for a back of the envelope calculation, it's 4 x width x scale x height x scale; e.g. 1000 x 1000 on 3x scale device can take ~36mb when you use it). If your memory isn't getting released, then use "debug memory graph" feature and identify any objects that should have been released and see if there are any unintended strong references lingering about. But the above code is unlikely to be the source of the problem re unreleased memory. – Rob May 03 '17 at 18:23
  • See http://stackoverflow.com/a/30993476/1271826 – Rob May 03 '17 at 18:30

1 Answers1

1

Finally I figure out the problem. UIGraphicsBeginImageContextWithOptions(sSelf.originalImage.size, NO, 0.0);

The first parameter is the size of the image and the last one is the scale factor. At the beginning I have already set the image size same as the original one. But I also set the scale as 0.0, which means it is set to the scale factor of the device’s main screen. So the result image is enlarged.

If I run the code several times, the result's size gets bigger and bigger, finally it use up the memory and I receive the warning.

Tony.Lee
  • 662
  • 1
  • 7
  • 14