IOS使用PicturePickerDelegate读取手机的照片
1.建立类实现代理PicturePickerDelegate
class WordEditController: UIViewController,PicturePickerDelegate{
//调用系统照片功能
@objc func pictuteChioce() {
if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary) {
// print("无法选择照片")
return
}
//显示照片窗口
let picker = UIImagePickerController()
//拍照 默认类型是照片选择
//.photoLibrary系统的枚举类型
picker.sourceType = .photoLibrary
// 设置代理
picker.delegate=self
//不允许编辑照片
picker.allowsEditing=false
present(picker,animated:true) {
}
}
//实现代理的方法
//拍照、图片、图片修改都回调这个方法
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
var scaleImage:UIImage?
//读取选择的图片,info[UIImagePickerController.InfoKey.editedImage]是编辑后的图片
//info[UIImagePickerController.InfoKey.originalImage]是原始图片
let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
if let imageTemp = image {
scaleImage = imageTemp.scaleToWith(width:600)
}
//判断是否可以使用,特殊情况选择的图片无法使用
if scaleImage == nil{
dismiss(animated: true, completion: nil)
let picAlertController:UIAlertController=UIAlertController(title:"此图不可用,请重新选择",message:nil,preferredStyle: .alert) let closeAction =UIAlertAction(title:"好的",style: .cancel,handler: { action in
return
})
picAlertController.addAction(closeAction)
picAlertController.dismiss(animated:true) {
}
self.present(picAlertController,animated:true)
return
}
//记录选择的照片,更改界面显示
自己的图片控件.uiImage = scaleImage
//自定义方法,保存图像到本应用目录
savePhotoInDocument(docImage:scaleImage!)
//关闭系统照片视图
dismiss(animated: true, completion: nil)
}
private func savePhotoInDocument(docImage:UIImage){
//保存到相册或者自己的目录,UIImageWriteToSavedPhotosAlbum调用后面的方法image()
// UIImageWriteToSavedPhotosAlbum(docImage, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
//保存到自己的目录
let imageName:String = "img_" + UUID().uuidString + ".png"
let fileManager =FileManager.default
let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString
let fileFullName = documentPath + imageName
//压缩图片 到50K
let compressData:Data= docImage.compressImageOnlength(maxLength:50)!
try? compressData.write(to:URL(fileURLWithPath: fileFullName))
}
//保存到相册
@objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
if let error = error {
let ac = UIAlertController(title: "图片保存失败", message: error.localizedDescription, preferredStyle: .alert)
ac.addAction(UIAlertAction(title:"好的",style: .default))
present(ac,animated:true)
}else{
let ac =UIAlertController(title:"截图已保存到照片",message:nil,preferredStyle: .alert)
ac.addAction(UIAlertAction(title:"好的",style: .default))
present(ac,animated:true)
}
}
}
网友评论