2012-08-08 81 views
1

我有NSImage,我想從它製作OpenGL紋理。所以我做了下面的工作:NSImage - > NSData - > NSBitmapImageRep breake .jpg圖像?

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

如果某些NSImage是.png,它可以正常工作。但是,如果某些NSImage是.jpg紋理正在被破壞。

隨着png格式,它看起來就像是:

enter image description here

而且相同的圖像,但.jpg格式的,它看起來像:

enter image description here

的哪些錯誤?

回答

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]; 
+0

但正如您在您的代碼中提到的那樣 'bestRepresentationForDevice' 已在Mac OS X v10.6中棄用。那麼這個代碼能在OS X 10.7 +上工作嗎? – hockeyman 2012-08-08 09:23:44

+0

如果bestRepresentationForDevice返回零[圖像表示]將爲您工作。 – 2012-08-08 09:25:35

+0

此代碼是否適合您? – 2012-08-08 09:27:09

0
  1. 的寬度和2中的一個紋理必須是功率的高度,即128,256,512,1024,等等
  2. 它看起來像您的圖像格式不是32位。
+0

我怎樣才能得到它的工作?我目前使用的圖像是Mac OS X最初添加的壁紙之一。它的大小是3200 x 2000. – hockeyman 2012-08-08 09:09:23

相關問題