繁体   English   中英

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

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

我做了一切从相机或画廊获取图像的工作,但是如何将该图像保存在数组或 realm 数据中以显示在其他 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保存到 realm。

获取图像

let savedImage = UIImage(data: imageData)

如果您不想在应用程序中保留图像而只想保存图像以在其他视图 controller 中显示,那么您可以将该图像传递给其他视图 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)

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

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

因此您可以在其他视图 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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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