加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift 3 实现拍照功能

发布时间:2020-12-14 06:14:05 所属栏目:百科 来源:网络整理
导读:编辑.plist文件,添加两个key-value,打开相机和相册的访问权限 1) 申请相机权限: keyNSCameraUsageDescription/keystringThis app will use camera./string 2) 申请相册权限 keyNSPhotoLibraryUsageDescription/keystringYou can select photos to attach t
编辑.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
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读