如何在不改变颜色空间的情况下获得UIImage负片颜色



所以,我遵循了这个问题中的建议:

如何给UIImage负色效果

但是当我进行转换时,颜色空间信息丢失并恢复为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格式来存储位图数据。如果不透明参数为YES,则位图将被视为完全不透明,并且其alpha通道将被忽略。

所以如果不将其更改为CGContext,这可能是不可能的?我发现,如果我将opaque参数设置为YES,那么它将删除alpha通道,这就足够了(我使用的tiff读取器无法处理ARGB图像)。不过,为了减小文件大小,我仍然希望只有灰度图像。

我发现解决这个问题的唯一方法是添加另一种方法,在反转后将图像重新转换为灰度。我添加了这种方法:

- (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;
}

如果有人有更整洁的方法,我很乐意听到!

最新更新