Home / IOS Development / ios – How to mask an image with MetalPetal and send out with transparency

ios – How to mask an image with MetalPetal and send out with transparency



I have an opaque image and an opaque mask image. Using MetalPetal and its MTIBlendWithMaskFilter I can create an output image that masks the input image correctly, but is opaque with a black background.

I want the output image to have an alpha channel, e.g. Instead of black pixels have transparent pixels.

func mt_blend(image: UIImage, with mask: UIImage) -> UIImage {
    let ciMaskImage = CIImage(cgImage: mask.cgImage!)
    let mtiMaskImage = MTIImage(ciImage: ciMaskImage, isOpaque: true)
    let mtiMask = MTIMask(content: mtiMaskImage)
    
    let ciImage = CIImage(cgImage: image.cgImage!)
    let mtiImage = MTIImage(ciImage: ciImage, isOpaque: true)

    let contextOptions = MTIContextOptions()
    let context = try! MTIContext(device: MTLCreateSystemDefaultDevice()!, options: contextOptions)

    let blendFilter = MTIBlendWithMaskFilter()
    blendFilter.inputMask = mtiMask
    blendFilter.inputBackgroundImage = mtiMaskImage
    blendFilter.inputImage = mtiImage
    
    let outputImage = try! context.makeCGImage(from: opacityFilter.outputImage!)
    return UIImage(cgImage: outputImage)
}

It seems that my misunderstanding or misuse of multipultingAlpha is the problem here.

Input image:

enter image description here

Mask image:

enter image description here

Starting image:

enter image description here


Source link