我正在嘗試編寫可以將現有圖像裁剪到某些指定大小/區域的代碼。我正在使用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
調用中使用的值,將非常感謝。
謝謝
謝謝,肯。這幫助我朝正確的方向邁出了一步。雖然我現在得到了一個輸出PNG,但它看起來與我所期望的大不相同。 看起來好像幾乎所有的像素都是黑色或白色。只有一些是灰色的。其次,png顯得非常像素化(超過了如果我放大原始圖像以將感興趣的區域放大到相似尺寸時發生的情況。 –
我最終希望能夠最終以編程方式在結果圖像上繪製/寫入文本,所以如果我理解了你的最後一條語句,聽起來好像'CGImage'可能不會允許這樣做。 –
正確,但你可以先創建一個CGImage,然後使用'CGBitmapContextCreateImage()'創建位圖上下文。 ,我錯誤地將這部分留給了我的答案。 –