简体   繁体   中英

How do I use a converted jpgData image in SwiftUI?

When the user selects an item from their photo library, the app saves the UIImage to the app's directory using the following code:

let imageUUID = UUID()
    let filename = getDocumentsDirectory().appendingPathComponent("\(imageUUID)")
    
    guard let uiImage = newImage else { return}
    
    if let jpegData = uiImage.jpegData(compressionQuality: 0.8) {
        try? jpegData.write(to: filename, options: [.atomicWrite, .completeFileProtection])
    }

How can I use the saved image in a view? Thanks!

First, you should save the UUID somewhere so that you can read the file later. This could be in UserDefaults , a JSON file, CoreData, or whatever, depending on your needs.

Suppose you have the path to the file stored in filePath , you can create an Image like this:

Image(uiImage: UIImage(contentsOfFile: filePath) ?? UIImage())

This will use an empty image as fallback if it failed to read the file.

Following code convert UIImage to Image in SwiftUI:

let uiImage = UIImage(contentsOfFile: path) ?? UIImage() // Access it from your storage
let image = Image(uiImage: uiImage)

There are different UIImage initializer methods available, you can use any one of them to get UIImage instance.

https://developer.apple.com/documentation/swiftui/image

You will like this tutorial of Coredata with SwiftUI : https://www.raywenderlich.com/9335365-core-data-with-swiftui-tutorial-getting-started

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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