我确实从相机或图库中选择了一张图片,以及如何保存该图片以在其他视图中显示?

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

我做了所有从相机或画廊获取图像的事情,但是如何将该图像保存在数组或领域数据中以显示在其他 viewController。

我该怎么做?

程序:-

 //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)

   }

您可以将图像另存为 Data,假设您有 pickedImage

let imageData = pickedImage.pngData()

imageData 保存到领域。

获取图片

let savedImage = UIImage(data: imageData)

如果您不想在应用程序中保留图像而只想保存图像以在其他视图控制器中显示,那么您可以将该图像传递给其他视图控制器。

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)

要将图像保存在文档目录中...

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)
            }
        }
    }

因此您可以在其他视图控制器中显示保存的图像。

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
}