简体   繁体   中英

i did Choose an image from camera or gallery and how to save that image to display in other View?

I did everything of getting image from camera or gallery, But how to save that image in array or in realm data to display in other viewController.

How can i do it?

Program:-

 //Camera to save image and display later
 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    showImage.image = info[UIImagePickerController.InfoKey.originalImage]
    imagePicker.dismiss(animated: true, completion: nil)

   }

You can save image as Data , let's say you have pickedImage .

let imageData = pickedImage.pngData()

save imageData to realm.

To get image

let savedImage = UIImage(data: imageData)

If you don't want to retain image in app and just want to save image to display in other view controller then you can just pass that image to other view controller.

let viewContrller = OtherViewController() //the view controller you need to pass image to
viewController.image = image //the image you need to pass to other view controller
navigationController(push: vc, animated: true)

To save image in document directory...

func saveImage(withName name: String) {
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

        // create the destination file url to save your image
        let fileURL = documentsDirectory.appendingPathComponent(fileName)

        // get your UIImage jpeg data representation and check if the destination file url already exists
        if let data = image.jpegData(compressionQuality:  1.0),
            !FileManager.default.fileExists(atPath: fileURL.path) {
            do {
                // writes the image data to disk
                try data.write(to: fileURL)
                print("file saved")
            } catch {
                print("error saving file:", error)
            }
        }
    }

So you can display the saved image in other view controller.

func getImageFromDocDir(named imgName: String) -> UIImage? {

    let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

    // create the destination file url to save your image
    let fileURL = documentsDirectory.appendingPathComponent(imgName)
    if FileManager.default.fileExists(atPath: fileURL.path) {

        do {
            let imgData = try Data(contentsOf: fileURL)
            return UIImage(data: imgData)
        } catch {
            print(error.localizedDescription)
        }
    }

    return nil
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM