我已经研究过替换图像中的颜色,但无法让它按照我需要的方式工作,因为我试图用除了一种颜色之外的所有颜色以及透明度来完成此操作。
我正在寻找的是一种获取图像并从该图像中分离出颜色(例如所有纯黑色)的方法。然后取出该分割部分并制作一个具有透明背景和分割部分的新图像。
(这里只是这个想法的一个例子,假设我想截取此页面的屏幕截图。使除纯黑色之外的所有其他颜色都是透明的,并将该新图像保存到库中,或将其放入 UIImageView 中)
我已经查看了 CGImageCreateWithMaskingColors 但似乎无法对透明部分执行我需要的操作,并且我并不真正理解 colorMasking 输入,除非您可以为其提供 {Rmin,Rmax,Gmin,Gmax,Bmin,Bmax } 颜色蒙版,但是当我这样做时,它会为所有内容着色。任何想法或意见都会很棒。
最佳答案
听起来您将必须访问底层字节并编写代码来直接处理它们。您可以使用CGImageGetDataProvider()
访问图像的数据,但不能保证该格式是您知道如何处理的格式。或者,您可以创建一个新的 CGContextRef
使用您知道如何处理的特定格式,然后将原始图像绘制到新上下文中,然后处理基础数据。这是执行您想要的操作的快速尝试(未编译):
- (UIImage *)imageWithBlackPixels:(UIImage *)image {
CGImageRef cgImage = image.CGImage;
// create a premultiplied ARGB context with 32bpp
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
size_t width = CGImageGetWidth(cgImage);
size_t height = CGImageGetHeight(cgImage);
size_t bpc = 8; // bits per component
size_t bpp = bpc * 4 / 8; // bytes per pixel
size_t bytesPerRow = bpp * width;
void *data = malloc(bytesPerRow * height);
CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host;
CGContextRef ctx = CGBitmapContextCreate(data, width, height, bpc, bytesPerRow, colorspace, bitmapInfo);
CGColorSpaceRelease(colorspace);
if (ctx == NULL) {
// couldn't create the context - double-check the parameters?
free(data);
return nil;
}
// draw the image into the context
CGContextDrawImage(ctx, CGRectMake(0, 0, width, height), cgImage);
// replace all non-black pixels with transparent
// preserve existing transparency on black pixels
for (size_t y = 0; y < height; y++) {
size_t rowStart = bytesPerRow * y;
for (size_t x = 0; x < width; x++) {
size_t pixelOffset = rowStart + x*bpp;
// check the RGB components of the pixel
if (data[pixelOffset+1] != 0 || data[pixelOffset+2] != 0 || data[pixelOffset+3] != 0) {
// this pixel contains non-black. zero it out
memset(&data[pixelOffset], 0, 4);
}
}
}
// create our new image and release the context data
CGImageRef newCGImage = CGBitmapContextCreateImage(ctx);
CGContextRelease(ctx);
free(data);
UIImage *newImage = [UIImage imageWithCGImage:newCGImage scale:image.scale orientation:image.imageOrientation];
CGImageRelease(newCGImage);
return newImage;
}
关于iphone - 按颜色分割 UIImage 并创建 2 个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4763685/