[英]iOS color to transparent in UIImage
如何清除 UIImage 的洋紅色部分並使其透明?
我已經查看了許多關於 SO 的答案和鏈接,但沒有任何效果(例如, 如何在 UIImage 上使一種顏色透明?答案 1 刪除了除紅色之外的所有內容,答案 2 顯然不起作用,因為為什么 CGImageCreateWithMaskingColors() 在這種情況? )。
更新:
如果我將 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 通道來讓它工作。
我制作了這個去除白色背景的靜態函數,您可以使用它用要刪除的顏色范圍替換蒙版:
+ (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;
}
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。
我在 CIImage 中做了這個,來自 Vision 的后處理是一個 pixelBuffer:
let ciImage = CIImage(cvPixelBuffer: pixelBuffer)
let filteredImage = ciImage.applyingFilter("CIMaskToAlpha")
self.picture.image = UIImage(ciImage: filteredImage)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.