Working with Images in Swift (iOS/macOS)
Working with images is one of the key tasks in developing mobile and desktop applications. In Swift for iOS and macOS, there are many built-in tools that allow you to load, display, process, and save images. In this article, we will take a detailed look at the main approaches and APIs that will help you work effectively with graphics on Apple platforms.
Main Classes for Working with Images
Different classes are used depending on the platform:
- iOS/tvOS/watchOS —
UIImage(UIKit) - macOS —
NSImage(AppKit)
Both classes provide similar capabilities but have differences in their APIs. For cross-platform development, you can use common protocols or extensions.
Loading Images
The simplest way is to load an image from the app's resources:
// iOSlet image = UIImage(named: "example")
// macOSlet image = NSImage(named: "example")To load from the network, use URLSession:
guard let url = URL(string: "https://example.com/image.jpg") else { return }
URLSession.shared.dataTask(with: url) { data, response, error in guard let data = data, error == nil else { return } DispatchQueue.main.async { // iOS let image = UIImage(data: data) // macOS let image = NSImage(data: data) }}.resume()Displaying Images
To display images on the screen, use the corresponding view components:
- iOS —
UIImageView - macOS —
NSImageView
// iOSlet imageView = UIImageView(image: UIImage(named: "photo"))imageView.contentMode = .scaleAspectFit
// macOSlet imageView = NSImageView(image: NSImage(named: "photo"))imageView.imageScaling = .scaleProportionallyUpOrDownImage Processing with Core Image
Core Image is a powerful framework for filtering and processing images. Let's look at a basic example of applying a filter:
import CoreImage
func applyFilter(to inputImage: CIImage) -> CIImage? { guard let filter = CIFilter(name: "CISepiaTone") else { return nil } filter.setValue(inputImage, forKey: kCIInputImageKey) filter.setValue(0.8, forKey: kCIInputIntensityKey) return filter.outputImage}
// Usagelet originalImage = CIImage(image: UIImage(named: "photo")!)!if let filteredImage = applyFilter(to: originalImage) { let context = CIContext() let cgImage = context.createCGImage(filteredImage, from: filteredImage.extent) let resultImage = UIImage(cgImage: cgImage!)}Popular Core Image filters:
CISepiaTone— sepiaCIGaussianBlur— Gaussian blurCIColorControls— adjusting brightness, contrast, saturationCIVignette— vignetting
Working with Pixels and CGImage
For low-level work with pixel data, use CGImage from Core Graphics:
func pixelColors(from image: UIImage) -> [[UIColor]]? { guard let cgImage = image.cgImage else { return nil } let width = cgImage.width let height = cgImage.height let colorSpace = CGColorSpaceCreateDeviceRGB() let bytesPerPixel = 4 let bytesPerRow = bytesPerPixel * width let bitsPerComponent = 8 var pixelData = [UInt8](repeating: 0, count: width * height * bytesPerPixel) guard let context = CGContext(data: &pixelData, width: width, height: height, bitsPerComponent: bitsPerComponent,