将图像保存到 .documentsDirectory,并作为 String 在本地 Realm 中存储路径

Saving image to .documentsDirectory, and as a String to store path in local Realm

我正在尝试将图像路径保存(解析?)到我的领域。为此,我尝试将图像作为 jpegData 保存到 documentDirectory 中。

我保存的图片不需要保存到用户的照片库中,只需要在应用程序本身中引用和显示。

首先,我不确定我是否为此采取了正确的方法。请指导我找到最合适的本地保存图像的解决方案。

我只看过少数几个网站、Stack Overflow 问题,几乎没有看过任何视频,所以有些事情告诉我有一种更有效的方法可以完成此任务。 , and 让我尝试将图像保存到目录中,尤其是最后的 SO 问题。

我有以下代码,但收到错误 "Value of type 'MyViewControllerName' has no member jpegData" 有什么想法可以解决这个错误或调整我的代码以允许它保存图像吗?

我试图保存的图像,从照片库或相机中选择后位于 selectedImageView

我已将 self.jpegData 更改为 UIImage.jpegDataselectedImageView.jpegData 并更改为 UIImageView.jpegData 出现大量错误,包括 Instance member 'jpegData' cannot be used on type 'UIImage'; did you mean to use a value of this type instead?.

@objc func saveTapped(_ sender: UIBarButtonItem) {
        self.performSegue(withIdentifier: "saveTappedSegue", sender: self)
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "saveTappedSegue" {
            let dest = segue.destination as! MyViewControllerName
            
            let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
            let fileName = "Image.jpg"
            let fileURL = documentsDirectory.appendingPathComponent(fileName)
            if let data = self.jpegData(compressionQuality: 1.0), //Error here
                !FileManager.default.fileExists(atPath: fileURL.path) {
                do {
                    try data?.write(to: fileURL!)
                    print("Image Saved")
                } catch {
                    print("error saving file:", error)
                }
            }
        
// Remaining code includes writing strings to realm not yet linked to the image.Path. This will be attempted once I can solve this error.

        }
    }

更新 - 添加了更多代码

 public var imagePickerController: UIImagePickerController?
    
    public var defaultImageUrl: URL?
       
       internal var selectedImage: UIImage? {
           get {
               return self.selectedImageView.image
           }
           
           set {
               switch newValue {
               case nil:
                   self.selectedImageView.image = nil
                   self.selectImageButton.isEnabled = true
                   self.selectImageButton.alpha = 1
                   
                   self.removeImageButton.isEnabled = false
                   self.removeImageButton.alpha = 0
               default:
                   self.selectedImageView.image = newValue
                   self.selectImageButton.isEnabled = false
                   self.selectImageButton.alpha = 0
                   
                   self.removeImageButton.isEnabled = true
                   self.removeImageButton.alpha = 1
               }
           }
       }

 //image input codes
    @IBOutlet weak var selectedImageContainer: UIView!
    @IBOutlet weak var selectedImageView: UIImageView!   
    @IBOutlet weak var selectImageButton: UIButton! {
        didSet {
            guard let button = self.selectImageButton else { return }
            button.isEnabled = true
            button.alpha = 1
        }
    }
    

    @IBOutlet weak var removeImageButton: UIButton! {
        didSet {
            guard let button = self.removeImageButton else { return }
            button.isEnabled = false
            button.alpha = 0
        }
    }

相关信息在viewDidLoad

override func viewDidLoad() {
        self.selectedImageView.contentMode = .scaleAspectFit
        self.selectImageButton.isEnabled = self.selectedImage == nil
        self.selectImageButton.alpha = 1

保存图像

//MARK: - "Select to Add Photo"
    @IBAction func selectImageButton(_ sender: Any) {
    
    if self.imagePickerController != nil {
            self.imagePickerController?.delegate = nil
            self.imagePickerController = nil
        }
        self.imagePickerController = UIImagePickerController.init()
        
        let alert = UIAlertController.init(title: "Select Source Type", message: nil, preferredStyle: .actionSheet)
        
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            alert.addAction(UIAlertAction.init(title: "Camera", style: .default, handler: { (_) in
                self.presentImagePicker(controller: self.imagePickerController!, source: .camera)
            }))
        }
        
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            alert.addAction(UIAlertAction.init(title: "Photo Library", style: .default, handler: { (_) in
                self.presentImagePicker(controller: self.imagePickerController!, source: .photoLibrary)
            }))
        }
 alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel))
        self.present(alert, animated: true)
    }
    
    internal func presentImagePicker(controller: UIImagePickerController , source: UIImagePickerController.SourceType) {
        controller.delegate = self
        controller.sourceType = source
        controller.allowsEditing = true
        self.present (controller, animated: true)
    }
    
    
    @IBAction func removeImageButtonAction(_ sender: UIButton) {
        self.selectedImage = nil
    }

在我的扩展中我有

extension AddNewMealVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {


    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
       
        if let image = info[.editedImage] as? UIImage {
            self.selectedImageView.image = image
        } else if let image = info[.originalImage] as? UIImage {
            self.selectedImageView.image = image
        }
           picker.dismiss(animated: true) {
            picker.delegate = nil
            self.imagePickerController = nil
        }
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
         picker.dismiss(animated: true) {
            picker.delegate = nil
            self.imagePickerController = nil
        }
    }
}

jpegData是UIImage的一个实例方法。让我们使用:

selectedImageView.image?.jpegData()