First of all You also need to release colorSpace
by calling CGColorSpaceRelease(colorSpace)
Memory allocated by calloc
can later be released in calling function using free(v_image.data)
(or whatever the returned variable is named in the calling method).
You can also change Your method implementation to get rid of CGContext
and get bytes from CGImage
using CGDataProviderRef
it would be something like:
-(vImage_Buffer)convertImage:(UIImage *)image
{
CGImageRef sourceRef = [image CGImage];
NSUInteger sourceWidth = CGImageGetWidth(sourceRef);
NSUInteger sourceHeight = CGImageGetHeight(sourceRef);
CGDataProviderRef provider = CGImageGetDataProvider(sourceRef);
CFDataRef bitmapData = CGDataProviderCopyData(provider);
unsigned char *sourceData = (unsigned char*)calloc(sourceHeight * sourceWidth * 4, sizeof(unsigned char));
NSUInteger bytesPerPixel = 4;
NSUInteger sourceBytesPerRow = bytesPerPixel * sourceWidth;
CFDataGetBytes(bitmapData, CFRangeMake(0, CFDataGetLength(bitmapData)), sourceData);
vImage_Buffer v_image = {
.data = (void *)sourceData,
.height = sourceHeight,
.width = sourceWidth,
.rowBytes = sourceBytesPerRow
};
CFRelease(bitmapData);
return v_image;
}
However I didn't check the performance.
I'd also suggest to rename Your method to something like vImageCreateFromImage
. You'll be aware that later You are responsible of cleaning up the memory.