2010-03-30 77 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