📱 Creating Thumbnail Images in Swift using UIKit
Creating thumbnail images is a great way to improve performance in iOS apps—especially when you're working with UITableView
or UICollectionView
. This post shows how to generate a resized and compressed version of a UIImage
using UIKit.
✂️ Why Use Thumbnail Images?
- Performance: Smaller images load faster and reduce memory usage.
- User Experience: Helps keep your UI smooth and responsive.
- Storage: Reduces app size and bandwidth when uploading/downloading images.
🛠 The Code
Here's a simple function to create a thumbnail from a UIImage
while preserving its aspect ratio and compressing the result:
swift
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
func createThumbnailImage(image: UIImage, size: CGSize) -> UIImage? {
let scale = max(size.width/image.size.width, size.height/image.size.height)
let width = image.size.width * scale
let height = image.size.height * scale
let newSize = CGSize(width: width, height: height)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
image.draw(in: CGRect(origin: CGPoint.zero, size: newSize))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let jpegData = newImage?.jpegData(compressionQuality: 0.8) {
return UIImage(data: jpegData)
} else {
return nil
}
}
}
Top comments (0)