如何在UIImageView中保存和加载图像?

时间:2017-03-21 06:29:31

标签: ios swift3 uiimageview xcode8

我正在尝试在xcode 8 swift 3中创建一个应用程序,其中用户使用imagePickerController添加图像然后当用户单击save或退出imagePickerController时我希望将图像保存在本地,所以下次应用程序是加载(例如在设备重启后)图像在那里。只是要清楚我不想将图像保存到相机胶卷。到目前为止,这是我的代码,没有任何保存或加载方法,(只是保存按钮参考)任何帮助将非常感激,因为我已经尝试这样做了很长时间。

import UIKit


class timetable: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

@IBOutlet var imageviewtimetable: UIImageView!


@IBAction func save(_ sender: Any) {


}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func selectImageFromPhotoLibrary(_ sender: Any) {

    let imagePickerController = UIImagePickerController()
    imagePickerController.sourceType = .photoLibrary
    imagePickerController.delegate = self
    present(imagePickerController, animated: true, completion: nil)


}



func imagePickerControllerDidCancel(_ picker: UIImagePickerController){
    dismiss(animated: true, completion:nil)
}


func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

    let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
    imageviewtimetable.image = selectedImage

    dismiss(animated: true,completion:nil)
}





}

1 个答案:

答案 0 :(得分:1)

有关信息:click here

将图像保存在文档目录

    func saveImageDocumentDirectory() {
        let fileManager = NSFileManager.defaultManager()
        let paths = (getDirectoryPath() as NSString).stringByAppendingPathComponent("apple.jpg")
        let image = UIImage(named: "apple.jpg")
        print(paths)
        let imageData = UIImageJPEGRepresentation(image!, 0.5)
        fileManager.createFileAtPath(paths as String, contents: imageData, attributes: nil)
    }

获取文档目录路径

    func getDirectoryPath() -> String {
        let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let documentsDirectory = paths[0]
        return documentsDirectory
    }

从文档目录中获取图像

    func getImage(){
        let fileManager = NSFileManager.defaultManager()
        let imagePath = (self.getDirectoryPath() as NSString).stringByAppendingPathComponent("apple.jpg")
        if fileManager.fileExistsAtPath(imagePath){
            self.imageView.image = UIImage(contentsOfFile: imagePath)
        } else {
            print("No Image")
        }
    }

创建目录

    func createDirectory(){
        let fileManager = NSFileManager.defaultManager()
        let paths = getDirectoryPath() as NSString).stringByAppendingPathComponent("customDirectory")
        if !fileManager.fileExistsAtPath(paths){
            try! fileManager.createDirectoryAtPath(paths, withIntermediateDirectories: true, attributes: nil)
        } else {
            print("Already dictionary created.")
        }
    }