CGImage to UIImage doesn't work

≯℡__Kan透↙ 提交于 2019-12-22 17:52:04

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/17576054/cgimage-to-uiimage-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!