SwiftUI: How to convert an Image to jpeg data?

Viewed 1879

In UIImage, there is the jpegData() method which turns the image into an NSData object of jpeg data.

What would the analogue be for the Image class?

1 Answers

The SwiftUI Image is analog of UIImageView, not UIImage. So if you need to operate with image model, you have to store it explicitly as UIImage and operate with it, providing into view as in below example:

struct ContentView: View {
   let imageModel: UIImage        // << model

   var body: some View {
      Image(uiImage: imageModel)  // << view
        .onTapGesture {
            // work with model

            let data = self.imageModel.jpegData(compressionQuality: 0.5)
            // .. do something with data
        }
   }
}
Related