ajf1000
ajf1000

Reputation: 429

SwiftUI: How to convert an Image to jpeg data?

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?

Upvotes: 8

Views: 6261

Answers (1)

Asperi
Asperi

Reputation: 257719

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

Upvotes: 12

Related Questions