Image Compressor for Swift
Free online image compressor with Swift code examples
Working with image compressor in Swift? Our free online image compressor helps Swift developers format, validate, and process data instantly. Below you will find Swift code examples using UIKit / AppKit (built-in) so you can achieve the same result programmatically in your own projects.
Try the Image Compressor Online
Use our free Image Compressor directly in your browser — no setup required.
Open Image CompressorSwift Code Example
import Foundation
#if canImport(UIKit)
import UIKit
func compressImage(at path: String, quality: CGFloat = 0.8) -> Data? {
guard let image = UIImage(contentsOfFile: path) else { return nil }
// Resize if needed
let maxSize = CGSize(width: 1920, height: 1080)
let ratio = min(maxSize.width / image.size.width,
maxSize.height / image.size.height, 1.0)
let newSize = CGSize(width: image.size.width * ratio,
height: image.size.height * ratio)
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.draw(in: CGRect(origin: .zero, size: newSize))
let resized = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resized?.jpegData(compressionQuality: quality)
}
if let data = compressImage(at: "input.jpg", quality: 0.8) {
try? data.write(to: URL(fileURLWithPath: "output.jpg"))
print("Compressed: \(data.count) bytes")
}
#endifQuick Setup
Library: UIKit / AppKit (built-in)
// Built-in frameworks — no installation neededSwift Tips & Best Practices
- UIImage.jpegData(compressionQuality:) controls JPEG quality
- Quality ranges from 0.0 (max compression) to 1.0 (best quality)
- On macOS, use NSImage with NSBitmapImageRep for compression