2014-04-23 56 views
1

我正在嘗試編寫可以將現有圖像裁剪到某些指定大小/區域的代碼。我正在使用DICOM圖像,並且我使用的API允許我直接獲取像素值。我已經將圖像中感興趣區域的像素值放入一個浮點數組(dstImage,如下)。使用CGBitmapContextCreate從像素數據創建圖像

我遇到麻煩的地方在於使用此像素數據實際構建/創建新的裁剪圖像文件。源圖像是灰度圖,但是我在網上找到的所有示例(如this one)都適用於RGB圖像。我試圖按照該鏈接中的示例進行操作,調整灰度並嘗試許多不同的值,但我仍然在CGBitmapContextCreate代碼行上發現錯誤,但仍不清楚這些值應該是什麼。

我的源圖像強度值高於255,所以我的印象是這不是8位灰度,而是16位灰度。

這裏是我的代碼:

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray(); 

CGContextRef context; 
context = CGBitmapContextCreate(dstImage, // pixel data from the region of interest 
           dstWidth, // width of the region of interest 
           dstHeight, // height of the region of interest 
           16, // bits per component 
           2 * dstWidth, // bytes per row 
           colorSpace, 
           kCGImageAlphaNoneSkipLast); 

CFRelease(colorSpace); 

CGImageRef cgImage = CGBitmapContextCreateImage(context); 
CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, 
              CFSTR("test.png"), 
              kCFURLPOSIXPathStyle, 
              false); 
CFStringRef type = kUTTypePNG; 
CGImageDestinationRef dest = CGImageDestinationCreateWithURL(url, 
                  type, 
                  1, 
                  0); 
CGImageDestinationAddImage(dest, 
          cgImage, 
          0); 
CFRelease(cgImage); 
CFRelease(context); 
CGImageDestinationFinalize(dest); 
free(dstImage); 

我不斷收到的錯誤是:

CGBitmapContextCreate: unsupported parameter combination: 16 integer bits/component; 32 bits/pixel; 1-component color space; kCGImageAlphaNoneSkipLast; 42 bytes/row. 

的最終目標是在dstImage創建從像素數據的圖像文件,並將其保存到硬盤。如需瞭解如何確定我應該在CGBitmapContextCreate調用中使用的值,將非常感謝。

謝謝

回答

0

首先,你應該熟悉的石英2D編程指南"Supported Pixel Formats" section:圖形上下文。

如果您的圖像數據是在float值的數組中,那麼它是32位的每個組件,而不是16個。因此,您必須使用kCGImageAlphaNone | kCGBitmapFloatComponents

但是,我相信Core Graphics會將浮點組件解釋爲介於0.0和1.0之間。如果你的值超出了這個範圍,你可能需要使用類似(value - minimumValue)/(maximumValue - minimumValue)的東西來轉換它們。另一種方法是使用CGColorSpaceCreateCalibratedGray()或使用CGImageCreate()創建CGImage並指定適當的decode參數,然後使用CGBitmapContextCreateImage()創建一個位圖上下文。實際上,如果你沒有繪製到你的位圖上下文中,反而應該創建一個CGImage

+0

謝謝,肯。這幫助我朝正確的方向邁出了一步。雖然我現在得到了一個輸出PNG,但它看起來與我所期望的大不相同。 看起來好像幾乎所有的像素都是黑色或白色。只有一些是灰色的。其次,png顯得非常像素化(超過了如果我放大原始圖像以將感興趣的區域放大到相似尺寸時發生的情況。 –

+0

我最終希望能夠最終以編程方式在結果圖像上繪製/寫入文本,所以如果我理解了你的最後一條語句,聽起來好像'CGImage'可能不會允許這樣做。 –

+0

正確,但你可以先創建一個CGImage,然後使用'CGBitmapContextCreateImage()'創建位圖上下文。 ,我錯誤地將這部分留給了我的答案。 –