CGImage to UIImage doesn't work

10,353

You should use alloc init like UIImage* myImage = [[UIImage alloc] initWithCGImage:myCGImage];

or you could try this:

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSUInteger width = CGImageGetWidth(image);
NSUInteger height = CGImageGetHeight(image);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
int size = height*width*bytesPerPixel;
unsigned char *rawData = malloc(size); 
CGContextRef context = CGBitmapContextCreate(rawData,width,height,bitsPerComponent,bytesPerRow,colorSpace,kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0,0,width,height),image);
UIImage *newImage = [UIImage imageWithCGImage:CGBitmapContextCreateImage(context)];
CGContextRelease(context);    
free(rawData);
Share:
10,353
Marti Serra Vivancos
Author by

Marti Serra Vivancos

Updated on June 04, 2022

Comments

  • Marti Serra Vivancos
    Marti Serra Vivancos almost 2 years

    I'm developing and iOS app for iPad and I use Grabkit in order to get images from Facebook, Twitter, Flicker and also the Camera Roll. To get the images from the last one, I need to convert a CGImage to an UIImage, but I'm having trouble with that. Is like if I didn't get any image, because when I use the UIImage later, the app crashes with this log:

     *** Terminating app due to uncaught exception 'CALayerInvalidGeometry', reason: 'CALayer position contains NaN: [nan 653]'
    

    I'm using the following code to convert the CGImage:

    UIImage* image = [UIImage imageWithCGImage:imgRef];
    

    So this code doesn't crash, but when I use the image created, it does. What is happening? Is the code wrong?