iOS - CGImageRef Potential Leak - ios

I have this code:
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
UIImage *outputimage = [UIImage imageWithCGImage:imageRef
scale:image.scale
orientation:UIImageOrientationUp];
and I get the warning:
Object leaked: object allocated and stored into 'imageRef' is not
referenced later in this execution path and has a retain count of +1
But I am using ARC and cannot use release or autoRelease. How to resolve this?

Just add this code
CGImageRelease(imageRef);
From CGImageCreateWithImageInRect document,
The resulting image retains a reference to the original image, which means you may release the original image after calling this function.
So,what you need to do is just call CGImageRelease to make it retain count -1

Related

EXC_BAD_ACCESS on accessing UIImage's size property

The image is an instance of UIImage. The first line executes with no problems, but the second one gives an EXC_BAD_ACCESS error at runtime.
NSLog(#"SCALE: %f", image.scale);
NSLog(#"TEST: %#", NSStringFromCGSize(image.size));
I can view the values of size property in Xcode by mouse-hovering it though.
Can you please help me in understanding what's wrong with it and/or what I might be missing?
Tested on a device and in simulator running iOS 8.
UPD: This is how I'm creating the image:
ALAssetRepresentation *rep = [asset defaultRepresentation];
CGFloat scale = 1.0f;
CGImageRef imageRef = [rep fullResolutionImage];
UIImage *image = [UIImage imageWithCGImage:imageRef scale:scale orientation:(UIImageOrientation)rep.orientation];
CGImageRelease(imageRef);
I just tried to delete the last line CGImageRelease(imageRef); and it seem to be fixed the problem. But I do need to release the CGImageRef, since I'm loading very large photos inside a loop and that takes a lot of memory.
So, I figured it out. The problem was that I released a CGImageRef that I didn't own.
CGImageRef imageRef = [rep fullResolutionImage];
If you get a CGImageRef by calling fullResolutionImage, you don't own it. Therefore, you don't need to release it yourself neither.
CGImageRelease(imageRef);
Removing the last line fixed the problem for me.

How to avoid "Received Memory warning" when changing the slider value in order to change the intensity of the image(coreImage)?

I am trying to implement a method that changes the tone of an image in accordance with the slider value, but when i change the slider value continuously it is showing memory warning and the app crashes.
This is my sample code, I tried using dispatch_async
-(void)valueChanged
{
float slideValue = slider.value;
NSLog(#"%0.f",slideValue);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0.5), ^{
dispatch_async(dispatch_get_main_queue(), ^{
[filter setValue:#(slideValue)
forKey:#"inputIntensity"];
CIImage *outputImage = [filter outputImage];
CGImageRef cgimg = [context createCGImage:outputImage
fromRect:[outputImage extent]];
UIImage *newImage = [UIImage imageWithCGImage:cgimg];
imageView.image = newImage;
});
});
}
You are leaking memory, what means that you are allocating objects that you are not releasing, hence the memory warnings.
Have you tried releasing the images after you have used them?
CGImageRelease(cgimg)
At the end of the method
Check the documentation for createCGImage:fromRect: API, for return value it says,
You are responsible for releasing the returned image when you no longer need it.
Which means you are leaking memory for cgimg instance. As suggested by Antonio MG you should release the reference at the end. The imageWithCGImage: will retain it, so no need to worry.
Hope that helps!

returning a UIImage where data behind it is released causing bad_access

I'm using ARC. I have something like this:
-(UIImage *)buildFullResImage
{
// blah blah does stuff to make a CGImage ref from some data...
CGImageRef imageRef = CGImageCreate(imageWidth, imageHeight, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);
// then make the uiimage from that
UIImage *myImage = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:UIImageOrientationUp];
CGImageRelease(imageRef);
CGDataProviderRelease(provider);
CGColorSpaceRelease(colorSpaceRef);
free(buffer);
return myImage;
}
Then somewhere else I do this...
UIImage *thisImage = [self buildFullResImage];
UIImage *resizedImage = [self imageWithImage:thisImage scaledToSize:CGSizeMake(newWidth, newHeight)];
And in the imageWithImage method I'm getting a bad_access crash because the actual image data (in buffer) was released back in buildFullResImage. I've tried a couple of different imageWithImage methods that can easily be found here on SO. It always crashes on whatever is accessing the passed uiimage's data. Usually it's crashing on like a:
CGContextDrawImage(bitmap, newRect, imageRef);
or
CGContextDrawImage(thisContext, CGRectMake(0.0, 0.0, imageSize.width, imageSize.height), image);
The UIImage when it comes across has an width and height and an address (is not null) but apparently no data behind it... because I released the data before returning the image. You can't release it after returning it.
I don't want to NOT release the buffer and the imageRef and have a leak. I don't want to duplicate code or merge the resizing with the building as I won't always need to use the resized version. I wanted modular code.
I know this seems like objective-c 101 but I've been fighting with it for hours. I have a dumb quick work around but I'd like to know the right way to do this.
UPDATE..
My dumb work around which is working is that I made buffer, the myImage, and the imageRef all global properties so they stay retained until I'm ready to release them. I can manage to release them after I'm done using them to save off the image or whatever I'm doing with it. But it seems like there would be a way to make the UIImage that I'm returning be it's own object with it's own control of it's underlying data.

Rules for managing CGImageRef memory?

What are the rules for managing memory for CGImageRefs with ARC? That is, can someone help me to the right documentation?
I am getting images from the photo library and creating a UIImage to display:
CGImageRef newImage = [assetRep fullResolutionImage];
...
UIImage *cloudImage = [UIImage imageWithCGImage:newImage scale:scale orientation:orientation];
Do I need to do CGImageRelease(newImage)?
I'm getting memory warnings but it doesn't seem to be a gradual buildup of objects I haven't released and I'm not seeing any leaks with Instruments. Puzzled I am.
No, you do not need to call CGImageRelease() on the CGImageRef returned by ALAssetRepresentation's convenience methods like fullResolutionImage or fullScreenImage. Unfortunately, at the current time, the documentation and header files for these methods does not make that clear.
If you create a CGImageRef yourself by using one of the CGImageCreate*() functions, then you own it and are responsible for releasing that image ref using CGImageRelease(). In contrast, the CGImageRefs returned by fullResolutionImage and fullScreenImage appear to be "autoreleased" in the sense that you do not own the image ref returned by those methods. For example, say you try something like this in your code:
CGImageRef newImage = [assetRep fullResolutionImage];
...
UIImage *cloudImage = [UIImage imageWithCGImage:newImage
scale:scale orientation:orientation];
CGImageRelease(newImage);
If you run the static analyzer, it will issue the following warning for the CGImageRelease(newImage); line:
Incorrect decrement of the reference count of an object that is not
owned at this point by the caller
Note that you will get this warning regardless of whether your project is set to use Manual Reference Counting or ARC.
In contrast, the documentation for the CGImage method of NSBitmapImageRep, for example, makes the fact that the CGImageRef returned is autoreleased more clear:
CGImage
Returns a Core Graphics image object from the receiver’s
current bitmap data.
- (CGImageRef)CGImage
Return Value
Returns an autoreleased CGImageRef opaque type based on the receiver’s
current bitmap data.

UIImage from CGImageRef

I am trying a simple test for a much more complex project but I am baffled as to why the code below is crashing and giving an EXC_BAD_ACCESS error?
This is called from a UIView.
- (void)testing {
NSString *imagePath = [[NSBundle mainBundle] pathForResource:#"ball.png" ofType:nil];
CGImageRef imageRef = [[[UIImage alloc]initWithContentsOfFile:imagePath]CGImage];
// CGImageRetain(imageRef);
UIImage *newImage = [[UIImage alloc]initWithCGImage:imageRef];
UIImageView *iv = [[UIImageView alloc]initWithImage:newImage];
[self addSubview:iv];
}
My guess is that the CGImageRef is not being retained but adding CGImageRetain(imageRef); makes no difference.
I should also note that this project has ARC turned on.
EDIT
I did a little bit more testing and have discovered that this is directly related to ARC as I created 2 basic projects including only the code above. The first with ARC turned off and it worked perfectly. The next with ARC turned on and BAM crash with the same error. The interesting thing is that I got an actual log error ONLY the first time I ran the project before the crash.
Error: ImageIO: ImageProviderCopyImageBlockSetCallback 'ImageProviderCopyImageBlockSetCallback' header is not a CFDictionary...
This line is the problem:
CGImageRef imageRef = [[[UIImage alloc]initWithContentsOfFile:imagePath]CGImage];
The created UIImage will be released immediately following this full-expression (e.g. after this line). So even trying to add a CGImageRetain() afterwards won't work.
The fundamental problem is the CGImageRef returned from CGImage is almost certainly an ivar of the UIImage and will be released when the UIImage is deallocted.
The generic way to fix this is to extend the lifetime of the UIImage. You can do this by placing the UIImage into a local variable and referencing it after your last reference to the CGImage (e.g. with (void)uiimageVar). Alternatively, you can retain the CGImageRef on that same line, as in
CGImageRef imageRef = CGImageRetain([[[UIImage alloc] initWithContentsOfFile:imagePath] CGImage]);
But if you do this, don't forget to release the imageRef when you're done.
You wrote this:
CGImageRef imageRef = [[[UIImage alloc]initWithContentsOfFile:imagePath]CGImage];
That line creates a UIImage, gets its CGImage property, and then releases the UIImage object. Since you're not retaining the CGImage on that line, the only owner of the CGImage is the UIImage. So when the UIImage is released and immediately deallocated, it deallocates the CGImage too.
You need to retain the CGImage before the UIImage is released. Try this:
CGImageRef imageRef = CGImageRetain([[UIImage alloc]initWithContentsOfFile:imagePath].CGImage);
and then at the end of the function:
CGImageRelease(imageRef);

Resources