How to fix error when save UIImage with SPRectangle on IOS 6.0

77 Views Asked by At

This function return a black image. I use the Sparrow Library.

This is my code :

-(UIImage *) saveRectangle:(SPRectangle*)rectangle
{
    int numberOfComponents = 8;
    int width = rectangle.width;
    int height = rectangle.height;

    NSInteger bufferLenght = width * height * numberOfComponents;


    NSMutableData * buffer= [NSMutableData dataWithLength:bufferLenght];

    glPixelStorei(GL_PACK_ALIGNMENT, 4); // force 4 byte alignment

    glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, [buffer mutableBytes]);


    CGDataProviderRef ref = CGDataProviderCreateWithData(NULL, [buffer mutableBytes], bufferLenght, NULL);
    CGImageRef iref = CGImageCreate(width, height, 8, 32, width * 4, CGColorSpaceCreateDeviceRGB(), kCGBitmapByteOrderDefault, ref, NULL, true, kCGRenderingIntentDefault);
    uint32_t* pixels = (uint32_t *)malloc(bufferLenght);
    CGContextRef context = CGBitmapContextCreate(pixels, width, height, 8, width*4, CGImageGetColorSpace(iref), kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Big);
    CGContextTranslateCTM(context, 0.0, height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextDrawImage(context, CGRectMake(0.0, 0.0, width, height), iref);
    CGImageRef outputRef = CGBitmapContextCreateImage(context);
    free(pixels);

    return [UIImage imageWithCGImage:outputRef];
}
1

There are 1 best solutions below

0
Soulfire On

The code you show has very little Sparrow code to it (other than the SPRectangle which is very akin to a CGRect). Sounds like you're trying to save a capture of a rectangular area of a Sparrow scene. Sparrow intends to abstract you from the OpenGL implementation details. Are you sure it wouldn't be easier to just use an SPRenderTexture? http://doc.sparrow-framework.org/core/Classes/SPRenderTexture.html

Also be sure you want to return an UIImage and not a SPImage. Hope it helps.