gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 11:24:56 25 4
gpt4 key购买 nike

我做了所有从相机或画廊获取图像的事情,但是如何将该图像保存在数组或领域数据中以显示在其他 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)

}

最佳答案

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

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

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

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

关于ios - 我确实从相机或图库中选择了一张图片,以及如何保存该图片以在其他 View 中显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58479676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com