1

我有 NSImage,我想从中制作 OpenGL 纹理。所以我做休耕:

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

如果 someNSImage 是 .png 它可以正常工作。但是如果 someNSImage 是 .jpg 纹理被破坏。

使用 .png 它看起来像这样:

在此处输入图像描述

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

在此处输入图像描述

怎么了?

4

2 回答 2

1

试试这个

@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];
于 2012-08-08T09:12:13.630 回答
0
  1. a 纹理的宽度和高度必须是 2 的幂,即 128、256、512、1024 等。
  2. 看起来您的图像格式不是 32 位的。
于 2012-08-08T08:44:45.703 回答