NSImage - > NSData - > NSBitmapImageRep破坏.jpg图像?

时间:2012-08-08 08:34:52

标签: objective-c opengl

我有NSImage,我想从中制作OpenGL纹理。所以我做了以下事情:

someNSData = [someNSImage TIFFRepresentation];
someNSBitmapImageRepData = [[NSBitmapImageRep alloc] initWithData:someNSData]

如果someNSImage是.png,那就可以了。但是如果某些NSImage是.jpg纹理被破坏了。

使用.png看起来像是:

enter image description here

同样的图像,但.jpg格式看起来像:

enter image description here

怎么了?

2 个答案:

答案 0 :(得分:1)

尝试this

@implementation  NSImage(NSImageToCGImageRef)
- (NSBitmapImageRep *)bitmapImageRepresentation
{
    NSBitmapImageRep *ret = (NSBitmapImageRep *)[self bestRepresentationForDevice:nil];

    if(![ret isKindOfClass:[NSBitmapImageRep class]])
    {
        ret = nil;
        for(NSBitmapImageRep *rep in [self representations])
            if([rep isKindOfClass:[NSBitmapImageRep class]])
            {
                ret = rep;
                break;
            }
    }

    // if ret is nil we create a new representation
    if(ret == nil)
    {
        NSSize size = [self size];

        size_t width         = size.width;
        size_t height        = size.height;
        size_t bitsPerComp   = 32;
        size_t bytesPerPixel = (bitsPerComp / CHAR_BIT) * 4;
        size_t bytesPerRow   = bytesPerPixel * width;
        size_t totalBytes    = height * bytesPerRow;

        NSMutableData *data = [NSMutableData dataWithBytesNoCopy:calloc(totalBytes, 1) length:totalBytes freeWhenDone:YES];

        CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);

        CGContextRef ctx = CGBitmapContextCreate([data mutableBytes], width, height, bitsPerComp, bytesPerRow, space, kCGBitmapFloatComponents | kCGImageAlphaPremultipliedLast);

        if(ctx != NULL)
        {
            [NSGraphicsContext saveGraphicsState];
            [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:ctx flipped:[self isFlipped]]];

            [self drawAtPoint:NSZeroPoint fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];

            [NSGraphicsContext restoreGraphicsState];

            CGImageRef img = CGBitmapContextCreateImage(ctx);

            ret = [[[NSBitmapImageRep alloc] initWithCGImage:img] autorelease];
            [self addRepresentation:ret];

            CFRelease(img);
            CFRelease(space);

            CGContextRelease(ctx);
        }
        else NSLog(@"%@ Couldn't create CGBitmapContext", self);
    }

    return ret;
}

@end

//in your code
NSBitmapImageRep *tempRep = [image bitmapImageRepresentation];

答案 1 :(得分:0)

  1. 纹理的宽度和高度必须是2的幂,即128,256,512,1024等。
  2. 看起来您的图片格式不是32位。