如何在Swift 3中保存带有图像的相机照片

时间:2016-10-28 02:23:08

标签: ios xcode camera swift3 photo

在我的主视图中,我有一个UIView,其中有一个imageView,其中相机预览被拉入,第二个imageView基本上是一个图形边框,覆盖了相机预览。

当用户点击" Save"我很难找到任何支持来保存这两个图像。按钮。

到目前为止,这是我的代码:

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var pickedImage: UIImageView!
@IBOutlet weak var photoFrame: UIImageView!
@IBOutlet weak var photoWrapper: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
}

@IBAction func saveAction(_ sender: UIButton) {
    let imageData = UIImageJPEGRepresentation(pickedImage.image!, 0.99)
    let compressedImage = UIImage(data: imageData!)
    UIImageWriteToSavedPhotosAlbum(compressedImage!, nil, nil, nil)
}

@IBAction func cameraAction(_ sender: UIButton) {
    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)
    }
}

@IBAction func libraryAction(_ sender: UIButton) {
    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary;
        imagePicker.allowsEditing = true
        self.present(imagePicker, animated: true, completion: nil)
    }
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
    pickedImage.image = image
    self.dismiss(animated: true, completion: nil)
}
}

现在,点击" cameraAction"按钮将显示相机,并允许您拍摄照片,当您点击"使用此照片"时,会将拍摄的照片加载到" pickedImage"图像视图。

理想情况下,我希望我的相框叠加也可以在相机视图中 - 但是 - 我们一次只能处理一个问题(除非有人在阅读这个问题时知道如何在同一个问题中实现这一点)回答)。

我主要关注的是获取它以便saveAction可以将照片和叠加图像捕获到一个中。现在,我可以看到代码在照片视图中创建了一个UIImageJPEGRepresentation ...所以我想最重要的问题是 - 我是否可以在其中添加第二个图像(我猜不到),或者,我是否必须利用其他方法将两张照片合二为一,然后调用UIImageJPEGRepresentation?

1 个答案:

答案 0 :(得分:1)

在游乐场中写了这个函数,它可以将一个图像叠加在另一个图像上。您可以在生成的合成图像上调用UIImageJPEGRepresentation。

    func composite(image:UIImage, overlay:(UIImage), scaleOverlay: Bool = false)->UIImage?{
        UIGraphicsBeginImageContext(image.size)
        var rect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
        image.draw(in: rect)
        if scaleOverlay == false {
            rect = CGRect(x: 0, y: 0, width: overlay.size.width, height: overlay.size.height)
        }
        overlay.draw(in: rect)
        return UIGraphicsGetImageFromCurrentImageContext()
    }