[英]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.我做了一切从相机或画廊获取图像的工作,但是如何将该图像保存在数组或 realm 数据中以显示在其他 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
.您可以将图像另存为
Data
,假设您已经pickedImage
。
let imageData = pickedImage.pngData()
save imageData
to realm.将
imageData
保存到 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.如果您不想在应用程序中保留图像而只想保存图像以在其他视图 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)
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.因此您可以在其他视图 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.