4

I have a function:

- (UIImage *) resizeImage:(UIImage *)image width:(CGFloat)resizedWidth height:(CGFloat)resizedHeight shouldCrop:(BOOL)crop
{
    CGImageRef imageRef = [image CGImage];
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef bitmap = CGBitmapContextCreate(NULL, resizedWidth, resizedHeight, 8, 4 * resizedWidth, colorSpace, (CGBitmapInfo) kCGImageAlphaPremultipliedFirst);

    CGContextDrawImage(bitmap, CGRectMake(0, 0, resizedWidth, resizedHeight), imageRef);
    CGImageRef ref = CGBitmapContextCreateImage(bitmap);

    if (crop) // for SmallImage (tableviewcell)
    {
        CGRect cropRect = CGRectMake(0, CGImageGetHeight(ref) * 0.5 - ((float) kIvHeight * 0.5), (float) kIvWidth, (float) kIvHeight);
        ref = CGImageCreateWithImageInRect(ref, cropRect);
    }

    UIImage * result = [UIImage imageWithCGImage:ref];

    CGContextRelease(bitmap);
    CGImageRelease(ref);
    CGImageRelease(imageRef);
    return result;
}

The line CGImageRelease(imageRef); causes my app to crash with EXC_BAD_ACCESS it seems to work when I remove the line - but would this not cause memory leaks?

Larme
  • 24,190
  • 6
  • 51
  • 81
Halpo
  • 2,982
  • 3
  • 25
  • 54
  • does this line somehow deallocate the original UIImage? (the image parameter) – Halpo Apr 16 '14 at 09:31
  • 2
    You have to call CGImageRelease only when you use CGImageCreate, Copy or Retain. you dont need to call CGImageRelease in your case – Sunny Shah Apr 16 '14 at 09:40

1 Answers1

2

You don't own the CGImageRef imageRef because you obtain it using [image CGImage] so you don't need to release it.

Take a look at this one as well: How do I release a CGImageRef in iOS

Community
  • 1
  • 1
Leo Chapiro
  • 13,678
  • 8
  • 61
  • 92