I have an image and I need to save it without loss of quality or resizing. The file size should be as small as possible. But I can't even save it with its original file size.
I have an image.jpg (file size 2.1Mb). I put it in bundle and read in a Swift code. After I extracted it to PNG with .pngData() - and save as .png the file size is 18.1 Mb - which is ridiculous, even if I remove the Alpha Channel - it still will have 9-12 Mb.
If I use .jpegData() - it is still much more than the source image Only if I get jpeg with the quality 0.65% - I can have 2.1Mb - the same as the source but with visible loss in quality.
Where is the solution? How to optimize it and save without quality losses and without file size inflating?
func foo() {
let bundleURL = Bundle.main.bundleURL
// Source file size: 2.1 MB
let assetURL = bundleURL.appendingPathComponent("sourceBundle.bundle/image.jpg")
let srcUImage = UIImage.init(contentsOfFile: assetURL.relativePath)
if let dataPng = srcUImage!.pngData() {
printSize(data: dataPng) // Size: 18.1 MB
}
if let dataJpg = srcUImage!.jpegData(compressionQuality: 1.0) {
printSize(data: dataJpg) // Size: 5.3 MB
}
if let dataJpg = srcUImage!.jpegData(compressionQuality: 0.65) {
printSize(data: dataJpg) // Size: 2.1 MB
}
}
func printSize(data: Data) {
let bcf = ByteCountFormatter()
bcf.allowedUnits = [.useMB]
bcf.countStyle = .file
let string = bcf.string(fromByteCount: Int64(data.count))
print("Size: \(string)")
}