在UIImage(或其派生物)中,如何用另一种颜色替换一种颜色? [英] In a UIImage (or its derivatives), how can I replace one color with another?
问题描述
例如,我有一个UIImage(从中我可以得到一个CGImage,CGLayer等,如果需要),我想要替换所有的红色像素(1,0,0)与蓝色(0, 0,1)。
For example, I have a UIImage (from which I can get a CGImage, CGLayer, etc., if needed), and I want to replace all of the red pixels (1, 0, 0) with blue (0, 0, 1).
我有代码来确定哪些像素是目标颜色(参见这是SO问题&答案),我可以替换rawData中的适当值,但是(a)我不知道如何从我的rawData缓冲区中获取UIImage,(b)它似乎可能缺少一个内置函数,将自动为我做所有这些,保存
I have code to figure out which pixels are the target color (see this SO question & answer), and I can substitute the appropriate values in rawData but (a) I'm not sure how to get a UIImage back from my rawData buffer and (b) it seems like I might be missing a built-in that will do all of this for me automatically, saving me oodles of grief.
谢谢!
推荐答案
我们将UIImage放入一个rawBits缓冲区中(参见原始问题中的链接),然后我们将缓冲区中的数据重新打包为我们喜欢的(即,将所有红色分量(每4个字节)设置为0,作为测试)
Ok, so we got the UIImage into a rawBits buffer (see link in original question), then we twiddled the data in the buffer to our liking (i.e., set all the red-components (every 4th byte) to 0, as a test), and now need to get a new UIImage representing the twiddled data.
我在 Erica Sudan的iPhone Cookbook ,第7章(图片),示例12(位图)。相关的调用是CGBitmapContextCreate(),相关代码是:
I found the answer in Erica Sudan's iPhone Cookbook, Chapter 7 (images), example 12 (Bitmaps). The relevant call was CGBitmapContextCreate(), and the relevant code was:
+ (UIImage *) imageWithBits: (unsigned char *) bits withSize: (CGSize)
size
{
// Create a color space
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
if (colorSpace == NULL)
{
fprintf(stderr, "Error allocating color space\n");
free(bits);
return nil;
}
CGContextRef context = CGBitmapContextCreate (bits, size.width,
size.height, 8, size.width * 4, colorSpace,
kCGImageAlphaPremultipliedFirst);
if (context == NULL)
{
fprintf (stderr, "Error: Context not created!");
free (bits);
CGColorSpaceRelease(colorSpace );
return nil;
}
CGColorSpaceRelease(colorSpace );
CGImageRef ref = CGBitmapContextCreateImage(context);
free(CGBitmapContextGetData(context));
CGContextRelease(context);
UIImage *img = [UIImage imageWithCGImage:ref];
CFRelease(ref);
return img;
}
希望对未来的网站spelunk有用!
Hope that's useful to future site spelunkers!
这篇关于在UIImage(或其派生物)中,如何用另一种颜色替换一种颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!