2010-03-30 94 views
15

有没有一种简单的方法来做到这一点,在10.5?将NSImage *转换为CGImageRef?

在10.6我可以使用NSImage中CGImageForProposedRect:NULL背景:NULL提示:NULL

如果我不使用1B黑白图像(如第4组TIFF),我可以使用位图,但cgbitmaps似乎不喜欢那个设置...有没有一个这样做的一般方法?

我需要这样做,因为我有一个IKImageView似乎只想添加CGImages,但我得到的都是NSImages。目前,我使用的是私有setImage:(NSImage中*)方法,我真的确实不想使用...

+0

你知道我在哪里可以得到如何使用CGImageForProposedRect一个例子:NULL上下文:NULL提示:NULL。我为第一个参数提供了一个NSRect,但是我得到的类型不匹配。 – Brian 2011-01-14 21:26:52

+0

我不知道我从来没有尝试过除NULL之外的任何东西......可能是CGRect而不是NSRect? – 2011-01-28 15:12:33

回答

27

发现了以下的解决方案上this page

NSImage* someImage; 
// create the image somehow, load from file, draw into it... 
CGImageSourceRef source; 

source = CGImageSourceCreateWithData((CFDataRef)[someImage TIFFRepresentation], NULL); 
CGImageRef maskRef = CGImageSourceCreateImageAtIndex(source, 0, NULL); 

所有方法似乎为10.4+,所以你应该没问题。

+7

是的,但不要称'TIFFRepresentation'数百次。根据'NSImage'的不同,它最终可能会在内存中创建完整的未压缩的图像数据副本。 – Alex 2010-03-30 21:48:17

+0

有趣。我会尝试并让你知道。 – 2010-03-31 15:10:04

+0

非常好,这似乎工作谢谢! – 2010-03-31 19:08:12

17

[这是漫长的路。你只能这样做,如果你仍然支持旧版本的OS X如果你需要10.6或更高版本,而不是just use the CGImage method]

  1. Create a CGBitmapContext.
  2. Create an NSGraphicsContext for the bitmap context.
  3. Set the graphics context as the current context.
  4. Draw the image.
  5. Create the CGImage from the contents of the bitmap context.
  6. 释放位图上下文。
+0

我试过这个,它似乎不适用于1位黑白图像(由于某种原因,mac真的不喜欢处理CCITT TIFF ...)或失去解决方案...因为我有一个NSImage,我不确定我实际上可以找到分辨率来找出如何制作更好的图形上下文... – 2010-03-31 15:09:29

+0

查看图像的'表示'数组。其中一个应该是位图图像代表。您可以以像素(而不是点)为单位查询该对象的大小,以及其他与栅格相关的事实。 – 2010-03-31 15:45:44

+3

彼得,你是我在SO上敬佩和信任的成员。感谢您分享的所有知识和经验,以及您展示它的全面性。 – MikeyWard 2012-09-10 10:00:29

12

下面是使用- CGImageForProposedRect:context:hints:更详细的解答:

NSImage *image = [NSImage imageNamed:@"image.jpg"]; 

NSRect imageRect = NSMakeRect(0, 0, image.size.width, image.size.height); 

CGImageRef cgImage = [image CGImageForProposedRect:&imageRect context:NULL hints:nil]; 
1

只是做这个用CGImageForProposedRect:context:hints: ...

NSImage *image; // an image 
NSGraphicsContext *context = [NSGraphicsContext currentContext]; 
CGRect imageCGRect = CGRectMake(0, 0, image.size.width, image.size.height); 
NSRect imageRect = NSRectFromCGRect(imageCGRect); 
CGImageRef imageRef = [image CGImageForProposedRect:&imageRect context:context hints:nil]; 
+0

您不需要此示例中所示的图形上下文。这是一个可选参数。 – user487158 2018-01-04 03:48:01