我正在使用UIImagePickerController来使用我的相机:
@objc func toggle() {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
//Define UIImagePickerController variable
let imagePicker = UIImagePickerController()
//Assign the delegate
imagePicker.delegate = self
//Set image picker source type
imagePicker.sourceType = .camera
//Allow Photo Editing
imagePicker.allowsEditing = true
//Present camera
UIApplication.topViewController()?.present(imagePicker, animated: true, completion: nil)
}
}
现在我试图捕获使用didFinishPickingMediaWithInfo方法拍摄的图像,我在网上得到了这个例子:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let imageUrl = info[UIImagePickerControllerOriginalImage] as! NSURL
let imageName = imageUrl.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let photoURL = NSURL(fileURLWithPath: documentDirectory)
let localPath = photoURL.appendingPathComponent(imageName!)
let image = info[UIImagePickerControllerOriginalImage]as! UIImage
let data = UIImagePNGRepresentation(image)
do
{
try data?.write(to: localPath!, options: Data.WritingOptions.atomic)
}
catch
{
// Catch exception here and act accordingly
}
UIApplication.topViewController()?.dismiss(animated: true, completion: nil);
}
但我将UIImagePickerControllerReferenceURL更改为UIImagePickerControllerOriginalImage,因为UIImagePickerControllerReferenceURL为零。但在我改变之后,我得到了这个致命的错误:
无法投放“UIImage'”类型的值(0x1b6b02b58)到' NSURL'
如何保存相机拍摄的图像?我做错了什么?
答案 0 :(得分:0)
编写如下代码,这将为您提供图像。
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
UIImagePickerControllerOriginalImage返回图片而不是NSURL
编写以下代码以获取iOS 11中的图像网址。从iOS 11开始,UIImagePickerControllerImageURL可用,之前有UIImagePickerControllerMediaURL键来获取图像网址。
if #available(iOS 11.0, *) {
if let imageURL = info[UIImagePickerControllerImageURL] as? URL {
print(imageURL)
}
} else {
if let imageUrl = info[UIImagePickerControllerMediaURL] as? URL {
print(imageUrl)
}
}
我希望这会对你有所帮助。
答案 1 :(得分:0)
正在寻找实施 Swift 4 +
的完整方法的人func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage{
imageView.image = pickedImage
}
imgPicker.dismiss(animated: true, completion: nil)
}
这将根据新语法返回original image
对于图片URL 和媒体URL ,您各自
let imgURL = info[UIImagePickerController.InfoKey.imageURL]
let mediaURL = info[UIImagePickerController.InfoKey.mediaURL]