Swift 3 实现拍照功能

前端之家收集整理的这篇文章主要介绍了Swift 3 实现拍照功能前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
编辑.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.",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
    }
原文链接:https://www.f2er.com/swift/321551.html

猜你在找的Swift相关文章