Swift 3 实现拍照功能

来源:互联网 发布:儿童 编程培训 编辑:程序博客网 时间:2024/05/01 00:41
编辑.plist文件,添加两个key-value,打开相机和相册的访问权限
1) 申请相机权限:

<key>NSCameraUsageDescription</key><string>This app will use camera.</string>

2) 申请相册权限
<key>NSPhotoLibraryUsageDescription</key><string>You can select photos to attach to reports.</string>


在xcode中拖一个UIImageview 控件


继承下面两个类

UINavigationControllerDelegate

UIImagePickerControllerDelegate


实现方法:
class yourController:..., UINavigationControllerDelegate, UIImagePickerControllerDelegate  {...}

1. 拍照按钮实现:
@IBAction func your_take_photo_action(_ sender: UIButton) {        imagePicker =  UIImagePickerController()        imagePicker.delegate = self        imagePicker.sourceType = .camera        present(imagePicker, animated: true, completion: nil)    }






2. 保存相册
@IBAction func save(_ sender: AnyObject) {        UIImageWriteToSavedPhotosAlbum(imageTake.image!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)    }




3. 实现以下两个开启相机和选中图片的回调函数
func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {        if let error = error {            // we got back an error!            let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)            ac.addAction(UIAlertAction(title: "OK", style: .default))            present(ac, animated: true)        } else {            let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)            ac.addAction(UIAlertAction(title: "OK", style: .default))            present(ac, animated: true)        }    }    //MARK: - Done image capture here    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {         imagePicker.dismiss(animated: true, completion: nil)        imageTake.image = info[UIImagePickerControllerOriginalImage] as? UIImage    }






最后如果希望转换成base64,可以使用以下函数
func UIImgToBase64(img:UIImage) ->String{        let imageData:NSData = UIImagePNGRepresentation(img)! as NSData        let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)        return strBase64    }


原创粉丝点击