如何将蒙版应用于保存图像(swift3)

Posted

技术标签:

【中文标题】如何将蒙版应用于保存图像(swift3)【英文标题】:How to apply mask to a save image (swift3) 【发布时间】:2017-04-04 14:20:36 【问题描述】:

我的代码执行以下操作:

    拍照并在图像视图中显示。 在照片库中使用 cgrect 以自定义大小保存图像视图。

但是我的问题是掩码没有被转移到l?.draw(in: CGRect(x: 10, y: 240.5, width: 435 , height: 435), blendMode: .normal, alpha: 1.0)。我要做的就是保存带有蒙版的照片。

import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate 
var screenView: UIImageView!

var image1 = UIImage(named: "w")
var image3 = UIImage(named: "w")
var image2 = UIImage(named: "w")
func cropImageIntoQuarterSquare(image: UIImage) -> UIImage? 
    let originalImageSize: CGSize = image.size
    let smallImageSize = CGSize(width: (originalImageSize.width + 40), height: (originalImageSize.height + 40))
    UIGraphicsBeginImageContext(smallImageSize)
    image.draw(at: CGPoint.zero)
    let imageResult = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return imageResult

var currentImageView: UIImageView?
@IBOutlet var photoDispaly: UIImageView!
override func viewDidLoad() 
    super.viewDidLoad()


func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) 
    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
    self.currentImageView?.image = image
    self.dismiss(animated: true)


func saveImage(image1: UIImage, image2: UIImage, image3: UIImage) -> UIImage? 

    screenView = UIImageView()

    let newSize = CGSize(width: 900, height: 1200)
    UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
    defer  UIGraphicsEndImageContext() 
    UIColor.black.setFill()
    UIBezierPath(rect: CGRect(origin: .zero, size: newSize)).fill()
    UIGraphicsGetImageFromCurrentImageContext()

    let l = photoDispaly.image

    let image = photoDispaly.image

    let maskingImage = UIImage(named: "mask5")

    photoDispaly.image = maskImage(image: image!, mask: maskingImage!)
    photoDispaly.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleBottomMargin, .flexibleRightMargin, .flexibleLeftMargin, .flexibleTopMargin]
    photoDispaly.contentMode = .scaleAspectFit // OR .scaleAspectFill
    photoDispaly.clipsToBounds = true

    l?.draw(in: CGRect(x: 10, y: 240.5, width: 435 , height: 435), blendMode: .normal, alpha: 1.0)

    let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

    screenView.frame = CGRect(x:0, y: 0, width: self.view.frame.width, height: self.view.frame.height)

    self.view.addSubview(screenView)
    return newImage

@IBAction func takePhot(_ sender: Any) 
    self.currentImageView = self.photoDispaly
    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self

        imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
        imagePicker.allowsEditing = false
        self.present(imagePicker, animated: true, completion: nil)
    



func maskImage(image:UIImage, mask:(UIImage))->UIImage
    let imageReference = image.cgImage
    let maskReference = mask.cgImage
    let imageMask = CGImage(maskWidth: maskReference!.width,
                            height: maskReference!.height,
                            bitsPerComponent: maskReference!.bitsPerComponent,
                            bitsPerPixel: maskReference!.bitsPerPixel,
                            bytesPerRow: maskReference!.bytesPerRow,
                            provider: maskReference!.dataProvider!, decode: nil, shouldInterpolate: true)
    let maskedReference = imageReference!.masking(imageMask!)
    let maskedImage = UIImage(cgImage:maskedReference!)
    return maskedImage



func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) 
    if let error = error 
          return
     else 
        return
    



@IBAction func savePhoto(_ sender: Any) 

    guard let croppedImage = cropImageIntoQuarterSquare(image: image2!),
        let combinedImage = saveImage(image1: image1!, image2: croppedImage, image3: croppedImage) else 

            return
    

    UIImageWriteToSavedPhotosAlbum(combinedImage, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)


【问题讨论】:

快速提示:将 cmets 添加到您的代码中以帮助其他人了解它应该做什么(也可以帮助您了解哪些是在做您认为应该做的事情)。此外,如果您显示您尝试使用的“面具”图像以及您期望的结果,这将有所帮助。 我发现代码必须在 funccropImageIntoQuarterSquare 中 【参考方案1】:
import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate 
var screenView: UIImageView!

var image1 = UIImage(named: "w")
var image3 = UIImage(named: "w")
var image2 = UIImage(named: "w")
func cropImageIntoQuarterSquare(image: UIImage) -> UIImage? 

    let image = photoDispaly.image

    let maskingImage = UIImage(named: "mask5")



    photoDispaly.image = maskImage(image: image!, mask: maskingImage!)
    photoDispaly.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleBottomMargin, .flexibleRightMargin, .flexibleLeftMargin, .flexibleTopMargin]
    photoDispaly.contentMode = .scaleAspectFit // OR .scaleAspectFill
    photoDispaly.clipsToBounds = true


    let originalImageSize: CGSize = image!.size
    let smallImageSize = CGSize(width: (originalImageSize.width + 40), height: (originalImageSize.height + 40))
    UIGraphicsBeginImageContext(smallImageSize)
    image?.draw(at: CGPoint.zero)
    let imageResult = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return imageResult

var currentImageView: UIImageView?
@IBOutlet var photoDispaly: UIImageView!
override func viewDidLoad() 
    super.viewDidLoad()




 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) 
    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
    self.currentImageView?.image = image
    self.dismiss(animated: true)




func saveImage(image1: UIImage, image2: UIImage, image3: UIImage) -> UIImage? 



    screenView = UIImageView()

    let newSize = CGSize(width: 900, height: 1200)
    UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
    defer  UIGraphicsEndImageContext() 
    UIColor.black.setFill()
    UIBezierPath(rect: CGRect(origin: .zero, size: newSize)).fill()
    UIGraphicsGetImageFromCurrentImageContext()



    let l = photoDispaly.image






      l?.draw(in: CGRect(x: 10, y: 240.5, width: 435 , height: 435), blendMode: .normal, alpha: 1.0)




    let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

    screenView.frame = CGRect(x:0, y: 0, width: self.view.frame.width, height: self.view.frame.height)

    self.view.addSubview(screenView)
    return newImage

@IBAction func takePhot(_ sender: Any) 
    self.currentImageView = self.photoDispaly
    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self




        imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
        imagePicker.allowsEditing = false
        self.present(imagePicker, animated: true, completion: nil)


    



func maskImage(image:UIImage, mask:(UIImage))->UIImage
    let imageReference = image.cgImage
    let maskReference = mask.cgImage
    let imageMask = CGImage(maskWidth: maskReference!.width,
                            height: maskReference!.height,
                            bitsPerComponent: maskReference!.bitsPerComponent,
                            bitsPerPixel: maskReference!.bitsPerPixel,
                            bytesPerRow: maskReference!.bytesPerRow,
                            provider: maskReference!.dataProvider!, decode: nil, shouldInterpolate: true)
    let maskedReference = imageReference!.masking(imageMask!)
    let maskedImage = UIImage(cgImage:maskedReference!)
    return maskedImage




func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) 
    if let error = error 
            return
     else 
        return

    


@IBAction func savePhoto(_ sender: Any) 

    guard let croppedImage = cropImageIntoQuarterSquare(image: image1!),
        let combinedImage = saveImage(image1: image1!, image2: croppedImage, image3: croppedImage)




        else 

            return
    

    UIImageWriteToSavedPhotosAlbum(combinedImage, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
    

【讨论】:

以上是关于如何将蒙版应用于保存图像(swift3)的主要内容,如果未能解决你的问题,请参考以下文章

将蒙版阵列 2d 应用到 3d

如何将 2 张图像重叠保存(swift3)

创建您自己的线性滤波器

Swift 3 中的 JSON 图像和核心数据 [关闭]

如何拍照并同时保存(swift3)

如何使用Swift选择图像的一部分,裁剪并保存?