Created
February 16, 2026 20:05
-
-
Save StewartLynch/ee83aabf6857922c3706293ca1e041a0 to your computer and use it in GitHub Desktop.
Resize and Optimize Image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| func resizedAndOptimizedImageData(from data: Data, maxWidth: CGFloat = 1000) -> Data? { | |
| guard let image = UIImage(data: data) else { return nil } | |
| let originalSize = image.size | |
| let scaleFactor = min(1, maxWidth / originalSize.width) | |
| let newSize = CGSize( | |
| width: originalSize.width * scaleFactor, | |
| height: originalSize.height * scaleFactor | |
| ) | |
| UIGraphicsBeginImageContextWithOptions(newSize, false, 1) | |
| image.draw(in: CGRect(origin: .zero, size: newSize)) | |
| let resizedImage = UIGraphicsGetImageFromCurrentImageContext() | |
| UIGraphicsEndImageContext() | |
| return resizedImage?.jpegData(compressionQuality: 0.8) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment