4

I'm trying to mask an image in swift. Here's my code:
(Normally, originalImg is an image that is loaded from UIImagePickerController and then cropped by UIGraphicsGetImageFromCurrentImageContext(), and
makedImage is an image that is drawn by the user, created by UIGraphicsGetImageFromCurrentImageContext())

func imageMasking(_ originalImg: UIImage, maskImage: UIImage) -> UIImage {
    let cgMaskImage = maskImage.cgImage!
    let mask = CGImage(maskWidth: cgMaskImage.width, height: cgMaskImage.height, bitsPerComponent: cgMaskImage.bitsPerComponent, bitsPerPixel: cgMaskImage.bitsPerPixel, bytesPerRow: cgMaskImage.bytesPerRow, provider: cgMaskImage.dataProvider!, decode: nil, shouldInterpolate: true)!
    return UIImage(cgImage: originalImg.cgImage!.masking(mask)!)
}

When I display the resulted UIImage to UIImageView, it works well. However, when I try to get the pngData() of the resulted UIImage, the image data is identical to originalImg.

I also tried to export the pngData() of the resulted image from Xcode, but it is still the same as originalImg.

Image: https://i.stack.imgur.com/pK8fK.jpg (then click the 'Export...' button and save as png image)

How can I really mask an image?

KeroppiMomo
  • 564
  • 6
  • 18

1 Answers1

5

Just draw a masked image into image context:

func drawImage(_ image: UIImage) -> UIImage?
    {
        guard let coreImage = image.cgImage else {
            return nil;
        }
        UIGraphicsBeginImageContext(CGSize(width: coreImage.width, height: coreImage.height))
        image.draw(in: CGRect(x: 0.0, y: 0.0, width: coreImage.width, height: coreImage.height))
        let resultImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return resultImage;
    }

Also you can draw image into bitmap context or image renderer and get result image.

Andrew Romanov
  • 4,774
  • 3
  • 25
  • 40
  • 1
    It works! Can you explain why you need to draw it to image context before calling `pngData()`? Also, why `UIImage` can show the masked image before drawing to image context? Thx! – KeroppiMomo Dec 29 '18 at 09:36
  • 3
    iPhone is a small device with small size of memory, but with strong GPU. Many components and methods of the SDK is lazy, for example if you create UIImage you will not load binary data into memory, data will be loaded late. Methods of CGImage, that can produce other images work in lazy way. You do not copy data when create CGImage via other CGImage. (In same way work CIImage, UIImage, CGImage, CGBitmapContextCreateImage, and many other components of the SDK) – Andrew Romanov Dec 29 '18 at 10:31