Skip to content

Instantly share code, notes, and snippets.

@StewartLynch
Created February 16, 2026 20:05
Show Gist options
  • Select an option

  • Save StewartLynch/ee83aabf6857922c3706293ca1e041a0 to your computer and use it in GitHub Desktop.

Select an option

Save StewartLynch/ee83aabf6857922c3706293ca1e041a0 to your computer and use it in GitHub Desktop.
Resize and Optimize Image
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