hockeyman
hockeyman

Reputation: 1183

glReadPixels -> NSData -> save image

I create NSBitmapImageRep witch I fill with glReadPixels information. It looks like this:

    NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL pixelsWide:width pixelsHigh:height bitsPerSample:8 samplesPerPixel:3 hasAlpha:NO isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:3 * width bitsPerPixel:0];
    glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, [imageRep bitmapData]);

and later turn it to NSData and write to file. But I get flipped upside down image. How can I fix it?

Upvotes: 1

Views: 722

Answers (2)

Volodymyr B.
Volodymyr B.

Reputation: 3441

bytesPerRow should be (width*3+3)&~3

Upvotes: 0

Vinny Rose
Vinny Rose

Reputation: 155

Draw into a flipped NSImage. This will draw the upsidedown image to the correct orientation. You then get the tiff representation of the NSImage which you can change to other image types using another NSBitmapImageRep with imageRepWithData:. Use the new image representation to make a new NSData object using representationUsingType:properties: and save the new NSData object to file.

    NSRect rect = self.bounds;
    NSSize size = rect.size;
    GLsizei width = (GLsizei)size.width;
    GLsizei height = (GLsizei)size.height;
    NSBitmapImageRep* imgRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL pixelsWide:width pixelsHigh:height bitsPerSample:8 samplesPerPixel:3 hasAlpha:NO isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:width*3 bitsPerPixel:0];
    glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, [imgRep bitmapData]);
#ifdef __MAC_10_8
    NSImage* image = [NSImage imageWithSize:size flipped:YES drawingHandler:^(NSRect dstRect){
        return [imgRep drawInRect:dstRect];
    }];
#else
    NSImage* image = [[NSImage alloc] initWithSize:size];
    [image lockFocusFlipped:YES];
    [imgRep drawInRect:rect];
    [image unlockFocus];
#endif
    NSData* tiff = [image TIFFRepresentation];

Upvotes: 1

Related Questions