Hi Forum,
I am new to openframeworks. I am running a problem and do not find any solution.
I want to convert UIImage to OFImage.
There is a class named “ofxiOSExtras” and it has a function named “ofxiOSUIImageToOFImage”
When I use this class to convert UIImage to OFImage then the function “ofxiOSUIImageToOFImage” run everything great but at third last line which is
outImage.setFromPixels(pixels, width, height, ofImageMode, true);
app crashes at this point.
All parameters to this function
pixels, width, height, ofImageMode, true
has some value but app is crashing
Can anyone suggest any way to convert UIImage to OFImage.
Here is the code to convert UIImage to OFImage.
bool ofxiOSUIImageToOFImage(UIImage *uiImage, ofImage &outImage, int targetWidth, int targetHeight) {
if(uiImage == nil) {
return false;
}
CGContextRef spriteContext;
CGImageRef cgImage = uiImage.CGImage;
int bytesPerPixel = CGImageGetBitsPerPixel(cgImage)/8;
if(bytesPerPixel == 3) bytesPerPixel = 4;
int width = targetWidth > 0 ? targetWidth : CGImageGetWidth(cgImage);
int height = targetHeight > 0 ? targetHeight : CGImageGetHeight(cgImage);
// Allocated memory needed for the bitmap context
GLubyte * pixels = (GLubyte *)malloc(width * height * bytesPerPixel);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
// Uses the bitmatp creation function provided by the Core Graphics framework.
spriteContext = CGBitmapContextCreate(pixels,
width,
height,
CGImageGetBitsPerComponent(cgImage),
width * bytesPerPixel,
colorSpace,
bytesPerPixel == 4 ? kCGImageAlphaPremultipliedLast : kCGImageAlphaNone);
CGColorSpaceRelease(colorSpace);
if(spriteContext == NULL) {
ofLogError(“ofxiOSExtras”) << “ofxiOSUIImageToOFImage(): CGBitmapContextCreate returned NULL”;
free(pixels);
return false;
}
CGContextSetBlendMode(spriteContext, kCGBlendModeCopy);
// After you create the context, you can draw the sprite image to the context.
ofLogVerbose(“ofxiOSExtras”) << “ofxiOSUIImageToOFImage(): about to CGContextDrawImage”;
CGContextDrawImage(spriteContext, CGRectMake(0.0, 0.0, (CGFloat)width, (CGFloat)height), cgImage);
// You don’t need the context at this point, so you need to release it to avoid memory leaks.
ofLogVerbose(“ofxiOSExtras”) << “ofxiOSUIImageToOFImage(): about to CGContextRelease”;
CGContextRelease(spriteContext);
ofImageType ofImageMode;
switch(bytesPerPixel) {
case 1:
ofImageMode = OF_IMAGE_GRAYSCALE;
break;
case 3:
ofImageMode = OF_IMAGE_COLOR;
break;
case 4:
default:
ofImageMode = OF_IMAGE_COLOR_ALPHA; break;
}
ofLogVerbose(“ofxiOSExtras”) << “ofxiOSUIImageToOFImage(): about to setFromPixels”;
outImage.setFromPixels(pixels, width, height, ofImageMode, true);
free(pixels);
return true;
}