简体   繁体   English

CGImage 到 UIImage 不起作用

[英]CGImage to UIImage doesn't work

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.我正在为 iPad 开发 iOS 应用程序,我使用 Grabkit 从 Facebook、Twitter、Flicker 和相机胶卷获取图像。 To get the images from the last one, I need to convert a CGImage to an UIImage, but I'm having trouble with that.要从最后一个中获取图像,我需要将 CGImage 转换为 UIImage,但是我遇到了麻烦。 Is like if I didn't get any image, because when I use the UIImage later, the app crashes with this log:就像我没有得到任何图像一样,因为当我稍后使用 UIImage 时,应用程序崩溃并显示此日志:

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

I'm using the following code to convert the CGImage:我正在使用以下代码来转换 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?代码有错吗?

You should use alloc init like UIImage* myImage = [[UIImage alloc] initWithCGImage:myCGImage];你应该使用 alloc init 像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);

Great advice, helped me fix my memory leaking issue.很好的建议,帮助我解决了内存泄漏问题。 Very important to free up allocated memory.释放分配的内存非常重要。 When you do:当你这样做时:

        unsigned char* buffer = (unsigned char*)malloc( dataSize );

also do this afterwards之后也这样做

        free(buffer);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM