Resize UIImage in Swift

Nikola Grujic
2 min readSep 27, 2023

--

Resizing UIImage is something that is often needed during the application development. It could be that the image needs to be resized before uploading or after downloading.

Fortunately, Apple made APIs that make it possible to resize images while preserving the aspect ratio.

Following extension of UIImage can be used to resize the image:

import UIKit
import AVFoundation

public extension UIImage {
/// Resize image while keeping the aspect ratio. Original image is not modified.
/// - Parameters:
/// - width: A new width in pixels.
/// - height: A new height in pixels.
/// - Returns: Resized image.
func resize(_ width: Int, _ height: Int) -> UIImage {
// Keep aspect ratio
let maxSize = CGSize(width: width, height: height)

let availableRect = AVFoundation.AVMakeRect(
aspectRatio: self.size,
insideRect: .init(origin: .zero, size: maxSize)
)
let targetSize = availableRect.size

// Set scale of renderer so that 1pt == 1px
let format = UIGraphicsImageRendererFormat()
format.scale = 1
let renderer = UIGraphicsImageRenderer(size: targetSize, format: format)

// Resize the image
let resized = renderer.image { _ in
self.draw(in: CGRect(origin: .zero, size: targetSize))
}

return resized
}
}

It can be used in the following way:

let uiImage = UIImage(data: data)
let resizedImage = uiImage.resize(1500, 1500)

Image object from SwiftUI can easily be instantiated from UIImage:

let image = Image(uiImage: resizedImage)

Test

It is practical to test the resizing function to confirm that the resulting image has the requested size and that the original image is unchanged.

For this test to work, it is necessary to add test .png image to the Resources of your project or to the swift package.

import XCTest

final class UIImageExtensionsTests: XCTestCase {
func testResize() {
guard let path = Bundle.module.path(forResource: "testImage", ofType: "png"),
let image = UIImage(contentsOfFile: path)
else {
XCTFail("Failed to load image from Resources.")
return
}

// Check original image
XCTAssertEqual(image.size.width, 3024.0)
XCTAssertEqual(image.size.height, 4032.0)

// Check resized image
let resizedImage = image.resize(1500, 1500)
XCTAssertEqual(resizedImage.size.width, 1125.0)
XCTAssertEqual(resizedImage.size.height, 1500.0)

// Check that the original image is unchanged
XCTAssertEqual(image.size.width, 3024.0)
XCTAssertEqual(image.size.height, 4032.0)
}
}

--

--

Nikola Grujic

Software Developer | Frontend | Mobile (iOS) | Desktop (macOS) | Swift, Objective-C | LinkedIn: linkedin.com/in/nikola-grujic-735a7284/