'Compress image size to below 1 MB in swift iOS

In iOS swift need to compress image size to below 1 MB by following this thread How to compress of reduce the size of an image before uploading to Parse as PFFile? (Swift) tried with below code it returns nil.

extension UIImage {
    // MARK: - UIImage+Compression
    func compressTo(_ expectedSizeBelowMb:Int) -> Data? {
        let sizeInBytes = expectedSizeBelowMb * 1024 * 1024
        var needCompress:Bool = true
        var imgData:Data?
        var compressingValue:CGFloat = 1.0
        while (needCompress && compressingValue > 0.0) {
            if let data:Data = self.jpegData(compressionQuality: compressingValue) {
                if data.count < sizeInBytes {
                    needCompress = false
                    imgData = data
                } else {
                    compressingValue -= 0.1
                }
            }
        }
        if let data = imgData, data.count < sizeInBytes {
                return data
        }
        return nil
    }
}

Can anyone suggest me correct way of compressing image size to below 1 MB.



Solution 1:[1]

You can try this code:

extension UIImage {

   func resizedTo1MB() -> UIImage? {
        guard let imageData = self.pngData() else { return nil }
        let megaByte = 1000.0
        
        var resizingImage = self
        var imageSizeKB = Double(imageData.count) / megaByte // ! Or devide for 1024 if you need KB but not kB
        
        while imageSizeKB > megaByte { // ! Or use 1024 if you need KB but not kB
            guard let resizedImage = resizingImage.resized(withPercentage: 0.5),
                  let imageData = resizedImage.pngData() else { return nil }
            
            resizingImage = resizedImage
            imageSizeKB = Double(imageData.count) / megaByte // ! Or devide for 1024 if you need KB but not kB
        }
        
        return resizingImage
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Taimoor Arif