Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CGImage of UIImage return NULL

I created a function for splitting an image into multiple images, but when I take take the CGImage of the UIImage, the CGImage returns NULL

NSArray* splitImage(UIImage* image,NSUInteger pieces) {

NSLog(@"width: %f, %zu",image.size.width,CGImageGetWidth(image.CGImage));
NSLog(@"%@",image.CGImage);
returns NULL
NSMutableArray* tempArray = [[NSMutableArray alloc]initWithCapacity:pieces];

CGFloat piecesSize = image.size.height/pieces;

for (NSUInteger i = 0; i < pieces; i++) {

    // take in account retina displays
    CGRect subFrame = CGRectMake(0,i * piecesSize * image.scale ,image.size.width * image.scale,piecesSize * image.scale);

    CGImageRef newImage = CGImageCreateWithImageInRect(image.CGImage,subFrame);

    UIImage* finalImage =[UIImage imageWithCGImage:newImage];

    CGImageRelease(newImage);

    [tempArray addObject:finalImage];

}

NSArray* finalArray = [NSArray arrayWithArray:tempArray];

[tempArray release];

return finalArray;



}
like image 693
Otium Avatar asked Apr 05 '12 04:04

Otium


3 Answers

Convert CGImage to UIImage with this and cgImage will not be null:

func convert(cmage:CIImage) -> UIImage
{       
    let context:CIContext = CIContext.init(options: nil)
    let cgImage:CGImage = context.createCGImage(cmage, from: cmage.extent)!        
    let image:UIImage = UIImage.init(cgImage: cgImage)        
    return image
}
like image 86
Ricardo Avatar answered Nov 18 '22 21:11

Ricardo


I have created UIImage from CGImage.

CIImage *ciImage = image.CIImage;
CIContext *context = [CIContext contextWithOptions:nil];
CGImageRef ref = [context createCGImage:ciImage fromRect:ciImage.extent];
UIImage *newImage = [UIImage imageWithCGImage:ref];

And now newImage.CGImage is not nil

like image 28
Andrew Bogaevskyi Avatar answered Nov 18 '22 21:11

Andrew Bogaevskyi


The CGImage property will return nil if the UIImage was created from another image such as an IOSurface or CIImage. To get around this in this particular case I can create a CGImage from an IOSurface using the c function then convert that to a UIImage.

UICreateCGImageFromIOSurface(IOSurfaceRef surface);
like image 44
Otium Avatar answered Nov 18 '22 22:11

Otium