2014-01-16 39 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; 
} 

如果有人有任何整洁的方法,我会很高兴听到他们!