Last active
November 2, 2018 10:33
-
-
Save vgoltv/bff5c70c459f670bc34d6b3f167d6978 to your computer and use it in GitHub Desktop.
method to create UIImage from CIImage and avoid memory leak of iOS9.0 described there: https://forums.developer.apple.com/thread/17142
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// initial swift code taken from https://forums.developer.apple.com/thread/17142 | |
// or you can kill current EAGLContext and create new one before CIContext creation | |
// but it is more expensive | |
// [EAGLContext setCurrentContext:nil]; | |
#import "UIImage-CIImageUtils.h" | |
@implementation UIImage (CIImageUtils) | |
static const size_t kComponentsPerPixel = 4; | |
static const size_t kBitsPerComponent = sizeof(unsigned char) * 8; | |
static void releasePixels(void *info, const void *data, size_t size) | |
{ | |
free((void*)data); | |
} | |
+ (UIImage *) imageFromCIImage:(CIImage *)img scale:(CGFloat)scale orientation:(UIImageOrientation)orientation | |
{ | |
int width = (int)img.extent.size.width; | |
int height = (int)img.extent.size.height; | |
long memsize = sizeof(unsigned char) * width * height * kComponentsPerPixel; | |
unsigned char *rawData = malloc(memsize); | |
CIContext *context = [CIContext contextWithOptions:@{kCIContextUseSoftwareRenderer: @NO}]; | |
CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB(); | |
[context render:img toBitmap:rawData rowBytes:width*kComponentsPerPixel bounds:img.extent format:kCIFormatRGBA8 colorSpace:rgb]; | |
CGDataProviderRef provider = CGDataProviderCreateWithData(nil, rawData, memsize, releasePixels); | |
CGImageRef imageFromContext = CGImageCreate(width, | |
height, | |
kBitsPerComponent, | |
kBitsPerComponent * kComponentsPerPixel, | |
width*kComponentsPerPixel, | |
rgb, | |
kCGBitmapByteOrderDefault | kCGImageAlphaLast, | |
provider, | |
NULL, | |
false, | |
kCGRenderingIntentDefault); | |
UIImage *outImage = [UIImage imageWithCGImage:imageFromContext scale:scale orientation:orientation]; | |
CGImageRelease(imageFromContext); | |
CGDataProviderRelease(provider); | |
CGColorSpaceRelease(rgb); | |
return outImage; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment