将图像保存到文件系统
Posted
技术标签:
【中文标题】将图像保存到文件系统【英文标题】:save image to file system 【发布时间】:2017-05-20 13:06:44 【问题描述】:在 main.storyboard 我有 UIImageView 和按钮。我想将通过相机拍摄的图像保存到文件系统。但是当我再次加载我的应用程序时,该图像消失了。请告诉我我做错了什么? 这是我的代码:
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate
@IBAction func useCamera(_ sender: UIButton)
let picker = UIImagePickerController()
picker.sourceType = .camera
self.present(picker, animated: true, completion: nil)
picker.delegate = self
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
override func didReceiveMemoryWarning()
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
picker.dismiss(animated: true, completion: nil)
if imageView.image == UIImage(named: "example.jpg")
if let data = UIImageJPEGRepresentation(imageView.image!, 0.8)
let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
try? data.write(to: filename)
func getDocumentsDirectory() -> URL
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
【问题讨论】:
【参考方案1】:你到底做错了什么,我不知道。我没有测试你的代码。这是一个有效的保存程序。它在当前在应用商店中的应用上进行了测试。
func save(image: UIImage, with fileName: String, and imageName: String?)
let documentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first
let imageStore = documentsDirectory?.appendingPathComponent(fileName)
let imageData = UIImagePNGRepresentation(image)
do
try imageData?.write(to: imageStore!)
catch
print("Couldn't write the image to disk.")
【讨论】:
以上是关于将图像保存到文件系统的主要内容,如果未能解决你的问题,请参考以下文章
如何将base64图像转换为图像并将其保存到文件系统[重复]