【问题标题】:iOS color to transparent in UIImageiOS颜色在UIImage中透明
【发布时间】:2011-11-29 12:54:22
【问题描述】:

如何清除 UIImage 的洋红色部分并使其透明?

我查看了关于 SO 的众多答案和链接,但没有任何效果(例如,How to make one color transparent on a UIImage? 答案 1 删除了除红色之外的所有内容,答案 2 显然由于Why is CGImageCreateWithMaskingColors() returning nil in this case? 而不起作用)。

更新:

如果我将 CGImageCreateWithMaskingColors 与 UIImage 一起使用,我会得到一个 nil 值。如果我删除 alpha 通道(我将图像表示为 JPEG 并将其读回) CGImageCreateWithMaskingColors 返回一个涂有黑色背景的图像。

Update2,代码:

返回零:

const float colorMasking[6] = {222, 255, 222, 255, 222, 255};
CGImageRef imageRef = CGImageCreateWithMaskingColors(anchorWithMask.CGImage, colorMasking);

NSLog(@"image ref %@", imageRef);
// this is going to return a nil imgref.

UIImage *image = [UIImage imageWithCGImage:imageRef];

返回黑色背景的图像(这是正常的,因为没有 alpha 通道):

UIImage *inputImage = [UIImage imageWithData:UIImageJPEGRepresentation(anchorWithMask, 1.0)];

const float colorMasking[6] = {222, 255, 222, 255, 222, 255};
CGImageRef imageRef = CGImageCreateWithMaskingColors(inputImage.CGImage, colorMasking);

NSLog(@"image ref %@", imageRef);
// imgref is NOT nil.

UIImage *image = [UIImage imageWithCGImage:imageRef];

更新3:

我通过在遮罩过程后添加 Alpha 通道使其工作。

【问题讨论】:

  • @MB 您是如何“在屏蔽过程后添加 Alpha 通道”的?

标签: ios uiimage


【解决方案1】:
UIImage *image = [UIImage imageNamed:@"image.png"];

const float colorMasking[6] = {1.0, 1.0, 0.0, 0.0, 1.0, 1.0};
image = [UIImage imageWithCGImage: CGImageCreateWithMaskingColors(image.CGImage, colorMasking)];

您收到 nil,因为您发送的参数无效。如果你打开 Apple 文档,你会看到:

组件
指定颜色或颜色范围的颜色组件数组 来掩盖图像。数组必须包含 2N 值 { min[1], max[1], ... min[N], max[N] } 其中 N 是 图像颜色空间中的分量。组件中的每个值都必须是 有效的图像样本值。如果图像具有整数像素分量,则 每个值必须在 [0 .. 2**bitsPerComponent - 1] 范围内(其中 bitsPerComponent 是图像的位数/分量)。如果图像 具有浮点像素分量,则每个值可以是任意值 浮点数,它是一个有效的颜色分量。

您可以通过按住 Option + 鼠标单击某个函数或类来快速打开文档,例如 CGImageCreateWithMaskingColors。

【讨论】:

  • 我刚试过这个,它返回一个完全透明的 uiimage。
  • 这是输入图像的样子:i.imgur.com/lxJdm.png(这是 png 版本,内部是来自 UIImagePicker 的 UIImage)
【解决方案2】:

我制作了这个删除白色背景的静态函数,你可以用它来替换你想要删除的颜色范围的遮罩:

+ (UIImage*) processImage :(UIImage*) image
{
    const float colorMasking[6]={222,255,222,255,222,255};
    CGImageRef imageRef = CGImageCreateWithMaskingColors(image.CGImage, colorMasking);
    UIImage* imageB = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    return imageB;
}

【讨论】:

  • 它正在处理我的项目,我正在删除白色范围。我认为您指定的颜色范围就像我使用的 222 -> 255 来删除红色一样。我可能无法 100% 理解它,但您可以在需要的范围内再试一次。
  • @khaledannajar 我已经使用了这段代码,它工作得很好,但是仍然无法从我在我的应用程序中以编程方式绘制的空白行的边框中删除一些白色像素
  • @keyur bhalodiya 您可以尝试更改白色的范围(使其更宽),除了我不知道如何帮助您。 :(
【解决方案3】:

我在 CIImage 中使用 Vision 的后处理作为 pixelBuffer:

    let ciImage = CIImage(cvPixelBuffer: pixelBuffer)
    let filteredImage = ciImage.applyingFilter("CIMaskToAlpha")
    self.picture.image = UIImage(ciImage: filteredImage)

【讨论】:

    猜你喜欢
    • 2012-05-03
    • 1970-01-01
    • 2010-10-12
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    相关资源
    最近更新 更多