I have an app that can choose photo from gallery and then upload it to the server.
I have 2 requirements from the server side:
- Compress image to 1mb max
- Image should have metada/exif data
To select image from gallery, I'm using new SwiftUI .photosPicker
Then I use .loadTransferable that returns me image Data.
photo.loadTransferable(type: Data.self) { result in }
When I load this Data to the server, EXIF/metadata is there. And that's great. But I need to compress image data.
I found a way to compress image data like this:
UIImage(data: data)?.jpegData(compressionQuality: 1)
And the problem is that after this compression, EXIF/metadata is LOST. UIImage cut it.
Question:
How to compress image Data without wrapping it to UIImage?
Or is there another way to compress image data and do not lose EXIF/metadata?
You're right, converting the image data to a UIImage and then compressing it with jpegData removes the EXIF data. Here's how you can achieve both compression and preserve EXIF data:
This approach uses CGImageSource and CGImageDestination to create a compressed version of the image while keeping the EXIF data intact.
However, there are several libraries like SDWebImage or SwiftyJPEG offer functionalities for compressing images while preserving metadata. These libraries might provide a more concise solution but come with the overhead of managing external dependencies