<error>:CGImageCreate:无效的图像位/像素:8 </error>

时间:2012-04-24 12:49:30

标签: cocoa-touch opencv uikit

我正在使用opencv和Xcode,我得到这个方法从IplImage转换为UIImage:

-(UIImage *)UIImageFromIplImage:(IplImage *)image {
NSLog(@"IplImage (%d, %d) %d bits by %d channels, %d bytes/row %s", image->width, image->height, image->depth, image->nChannels, image->widthStep, image->channelSeq);

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSData *data = [NSData dataWithBytes:image->imageData length:image->imageSize];
CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge  CFDataRef)data);
CGImageRef imageRef = CGImageCreate(image->width, image->height,
                         image->depth, image->depth * image->nChannels, image->widthStep,
colorSpace, kCGImageAlphaPremultipliedLast|kCGBitmapByteOrderDefault,
provider, NULL, false, kCGRenderingIntentDefault);
UIImage *ret = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:UIImageOrientationUp];
CGImageRelease(imageRef);
CGDataProviderRelease(provider);
CGColorSpaceRelease(colorSpace);
return ret;
}

问题是,当我将任何图像传递给此方法(png,jpg,tiff)时,会出现此错误 :CGImageCreate:无效的图像位/像素:8,请帮我解决这个错误,谢谢。

2 个答案:

答案 0 :(得分:1)

根据我在我的应用中所做的,您实际上需要在图像数据中提供alpha值。我所做的是从opencv结构中获取数据,添加alpha值,并创建CGImage。这是我在C ++ API中使用的代码(如果你坚持使用C只是用指向第y行第一个像素的指针替换对aMat.ptr&lt;&gt;(y)的调用):

// Colorspace
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

 unsigned char* data = new unsigned char[4*aMat.cols*aMat.rows];
 for (int y = 0; y < aMat.rows; ++y)
 {
     cv::Vec3b *ptr = aMat.ptr<cv::Vec3b>(y);
     unsigned char *pdata = data + 4*y*aMat.cols;

     for (int x = 0; x < aMat.cols; ++x, ++ptr)
     {
         *pdata++ = (*ptr)[2];
         *pdata++ = (*ptr)[1];
         *pdata++ = (*ptr)[0];
         *pdata++ = 0;
     }
 }

 // Bitmap context
 CGContextRef context = CGBitmapContextCreate(data, aMat.cols, aMat.rows, 8, 4*aMat.cols, colorSpace, kCGImageAlphaNoneSkipLast);

 CGImageRef cgimage = CGBitmapContextCreateImage(context);

 CGColorSpaceRelease(colorSpace);
 CGContextRelease(context);
 delete[] data;

洗牌部分是必要的,因为OpenCV处理BGR图像,而Quartz需要RGB。

答案 1 :(得分:1)

如果您的图像是灰色的(不是RGBA),请使用:

colorSpace = CGColorSpaceCreateDeviceGray();