2014-01-16 77 views
0

所以,我跟着這個問題的建議:如何獲得UIImage的負顏色不改變顏色空間

how to give UIImage negative color effect

但是當我做了轉換,色彩空間信息丟失,並恢復到RGB。 (我想要灰色)。

如果我在NSLogCGColorSpaceRef之前和之後給出的代碼,它證實了這一點。

CGColorSpaceRef before = CGImageGetColorSpace([imageView.image CGImage]); 
NSLog(@"%@", before); 

UIGraphicsBeginImageContextWithOptions(imageView.image.size, YES, imageView.image.scale); 

CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeCopy); 

[imageView.image drawInRect:CGRectMake(0, 0, imageView.image.size.width, imageView.image.size.height)]; 

CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeDifference); 

CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(),[UIColor whiteColor].CGColor); 

CGContextFillRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, imageView.image.size.width, imageView.image.size.height)); 

imageView.image = UIGraphicsGetImageFromCurrentImageContext(); 

UIGraphicsEndImageContext(); 

CGColorSpaceRef after = CGImageGetColorSpace([imageView.image CGImage]); 
NSLog(@"%@", after); 

是否有任何方法來保留顏色空間信息,或者,如果沒有,我怎麼能改變它之後呢?

編輯:在閱讀文檔UIGraphicsBeginImageContextWithOptions它說:

對於iOS 3.2中創建位圖和後來的繪圖環境使用預乘ARGB格式存儲的位圖數據。如果opaque參數爲YES,則位圖將被視爲完全不透明,並忽略其Alpha通道。

所以也許這是不可能的,沒有改變它爲CGContext?我發現如果我將opaque參數設置爲YES,那麼它將刪除足夠的alpha通道(我正在使用的tiff閱讀器無法處理ARGB圖像)。儘管爲了減小文件大小,我仍然只想要一個灰度圖像。

回答

2

我發現解決這個問題的唯一方法是添加另一種方法,在將圖像反轉後將圖像重新轉換爲灰度。我添加了這種方法:

- (UIImage *)convertImageToGrayScale:(UIImage *)image 
{ 
// Create image rectangle with current image width/height 
CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height); 

// Grayscale color space 
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray(); 

// Create bitmap content with current image size and grayscale colorspace 
CGContextRef context = CGBitmapContextCreate(nil, image.size.width, image.size.height, 8, 0, colorSpace, kCGImageAlphaNone); 

// Draw image into current context, with specified rectangle 
// using previously defined context (with grayscale colorspace) 
CGContextDrawImage(context, imageRect, [image CGImage]); 

// Create bitmap image info from pixel data in current context 
CGImageRef imageRef = CGBitmapContextCreateImage(context); 

// Create a new UIImage object 
UIImage *newImage = [UIImage imageWithCGImage:imageRef]; 

// Release colorspace, context and bitmap information 
CGColorSpaceRelease(colorSpace); 
CGContextRelease(context); 
CFRelease(imageRef); 

// Return the new grayscale image 
return newImage; 
} 

如果有人有任何整潔的方法,我會很高興聽到他們!