Downsample Photos For The Crop You Actually Display

A profile photo looks sharp in the picker and soft inside its square avatar. You downsampled it to the avatar’s pixel size. You remembered the display scale. Then scaledToFill() enlarged it anyway.

The image has complied with the request. Unfortunately, it was the wrong request.

A thumbnail’s longest edge and the pixels needed for a crop are different measurements. We’ll calculate the latter, let Image I/O apply the photo’s orientation, and reject requests that would require an oversized decode. This fills in the crop-sizing gap in our bounded thumbnail decoder; that article covers shared decoding and cache budgets.

The missing pixels are on the short edge

Consider a 4,000 × 3,000 photo displayed in a 160 × 160 point avatar on a 3× display. The visible square needs 480 × 480 pixels.

Setting Image I/O’s maximum edge to 480 produces a 480 × 360 thumbnail. Filling the square then enlarges its 360-pixel height to 480 pixels. Higher interpolation quality cannot recover detail that the thumbnail already discarded.

Instead, we need a 640 × 480 thumbnail. The view can crop its sides without enlarging it.

Request for that photoThumbnailWhat the view does
Maximum edge: 480480 × 360Enlarges before cropping to a 480-pixel square
Maximum edge: 640640 × 480Crops the sides at the requested pixel density
Full original4,000 × 3,000Holds far more pixels than this avatar needs

This is an established API with a current use case. Apple’s WWDC26 high-resolution capture session discusses the processing and memory tradeoffs of today’s large photos. Our work begins after capture: choosing the pixels needed for one display rectangle.

The Stack Overflow question about resizing without loading the whole image already has Image I/O answers. Mehmet Baykar’s downsampling walkthrough also explains why compressed file size doesn’t describe decoded image cost. This example extends the familiar longest-edge recipe with crop geometry and explicit rejection behavior; downsampling itself is not a new discovery.

Calculate after accounting for orientation

Let the oriented source dimensions be w × h, and the destination pixel dimensions be tw × th.

For aspect fill, the required scale factor is max(tw / w, th / h): both destination dimensions must be covered. Aspect fit uses the smaller ratio because the whole image must fit inside the destination. Apple’s image-fitting guide explains that display distinction.

Image I/O accepts a maximum pixel dimension, so we pass the source’s longest edge multiplied by the fill factor, rounded up.

Orientation matters before that calculation. EXIF orientations 5 through 8 swap the displayed width and height. Mirroring doesn’t change the dimensions, but it still needs to be applied to the pixels. Read the dimensions to plan the decode; let Image I/O’s transform option perform the actual rotation and mirroring.

The two Swift blocks below form one file. They use Swift 6.4.2, target iOS 17 / macOS 14, and were verified with Xcode 27.2 RC. The explicit nonisolated types keep the geometry independent of the project’s default actor isolation. Download the complete sample and checks to reproduce the examples.

import CoreGraphics
import Foundation
import ImageIO

nonisolated enum FillThumbnailError: Error {
    case invalidRequest, unreadableImage, invalidMetadata
    case sourceTooSmall, decodeBudgetExceeded, decodeFailed
    case insufficientPixels
}

nonisolated struct FillThumbnailPlan {
    let targetWidth: Int
    let targetHeight: Int
    let maximumEdge: Int

    init(sourceWidth: Int, sourceHeight: Int, orientation: Int,
         pointSize: CGSize, displayScale: CGFloat) throws {
        let requestedWidth = ceil(pointSize.width * displayScale)
        let requestedHeight = ceil(pointSize.height * displayScale)
        // A product policy for this example, not an Image I/O limit.
        let edgeLimit = 4096
        guard pointSize.width.isFinite, pointSize.height.isFinite,
              displayScale.isFinite, pointSize.width > 0,
              pointSize.height > 0, displayScale > 0,
              requestedWidth.isFinite, requestedHeight.isFinite,
              requestedWidth >= 1, requestedHeight >= 1,
              requestedWidth <= CGFloat(edgeLimit),
              requestedHeight <= CGFloat(edgeLimit) else {
            throw FillThumbnailError.invalidRequest
        }
        guard sourceWidth > 0, sourceHeight > 0,
              (1...8).contains(orientation) else {
            throw FillThumbnailError.invalidMetadata
        }
        let swapsAxes = (5...8).contains(orientation)
        let width = CGFloat(swapsAxes ? sourceHeight : sourceWidth)
        let height = CGFloat(swapsAxes ? sourceWidth : sourceHeight)
        let factor = max(requestedWidth / width, requestedHeight / height)
        guard factor <= 1 else { throw FillThumbnailError.sourceTooSmall }
        let edge = ceil(max(width, height) * factor)
        guard edge <= CGFloat(edgeLimit) else {
            throw FillThumbnailError.decodeBudgetExceeded
        }
        targetWidth = Int(requestedWidth)
        targetHeight = Int(requestedHeight)
        maximumEdge = Int(edge)
    }
}

actor FillThumbnailDecoder {
    func decode(file: URL, pointSize: CGSize,
                displayScale: CGFloat) throws -> CGImage {
        try Task.checkCancellation()
        guard file.isFileURL,
              let source = CGImageSourceCreateWithURL(
                file as CFURL,
                [kCGImageSourceShouldCache: false] as CFDictionary
              ) else { throw FillThumbnailError.unreadableImage }

        let index = CGImageSourceGetPrimaryImageIndex(source)
        guard let metadata = CGImageSourceCopyPropertiesAtIndex(source, index, nil)
                as? [CFString: Any],
              let width = metadata[kCGImagePropertyPixelWidth] as? NSNumber,
              let height = metadata[kCGImagePropertyPixelHeight] as? NSNumber else {
            throw FillThumbnailError.invalidMetadata
        }
        let orientation = (metadata[kCGImagePropertyOrientation] as? NSNumber)?.intValue ?? 1
        let plan = try FillThumbnailPlan(
            sourceWidth: width.intValue, sourceHeight: height.intValue,
            orientation: orientation, pointSize: pointSize,
            displayScale: displayScale
        )
        let options: CFDictionary = [
            kCGImageSourceCreateThumbnailFromImageAlways: true,
            kCGImageSourceCreateThumbnailWithTransform: true,
            kCGImageSourceShouldCacheImmediately: true,
            kCGImageSourceThumbnailMaxPixelSize: plan.maximumEdge,
        ] as CFDictionary
        guard let image = CGImageSourceCreateThumbnailAtIndex(source, index, options) else {
            throw FillThumbnailError.decodeFailed
        }
        try Task.checkCancellation()
        // Image I/O has returned actual pixels: verify them, not just our request.
        guard image.width >= plan.targetWidth,
              image.height >= plan.targetHeight else {
            throw FillThumbnailError.insufficientPixels
        }
        return image
    }
}

The 4,096-pixel edge limit is our policy, not Apple’s limit. We reject a source too small to cover the destination without enlargement. We also reject a request whose fill calculation exceeds the budget, even when the visible destination is small.

For example, filling a 480-pixel square from a 10,000 × 500 panorama requires a 9,600 × 480 thumbnail before cropping. Silently clamping that to 4,096 would reintroduce the enlargement we were trying to avoid. A product can offer aspect fit, accept a lower-resolution preview explicitly, or obtain a pre-cropped rendition from its image service. It should choose that tradeoff deliberately.

This helper returns the whole downsampled image. It doesn’t create a cropped file or select a face-aware focal point. It uses the source’s primary image, and is intended for ordinary still photos with square pixels. Animation, RAW development, HDR preservation and unusual pixel-aspect metadata need their own format policy.

CreateThumbnailFromImageAlways asks Image I/O to generate from the full image rather than depend on an embedded preview. It doesn’t mean we first construct a full-size UIImage. The source cache is disabled, and the thumbnail is decoded inside the actor. The returned dimensions are checked too: an unexpectedly undersized result becomes an error rather than a quietly enlarged success.

Match the decode request to the view

The decoder can’t infer your eventual layout. A 160-point avatar and a 320-point card require different requests, even if they share the same source file.

This small view uses the current SwiftUI environment’s display scale. Keep one decoder at the feature level and pass it to the rows. The actor serializes its synchronous decode calls; a new decoder per row would lose that limit.

import SwiftUI

@MainActor
struct CroppedPhoto: View {
    let file: URL // Keep this file unchanged for this view's lifetime.
    let decoder: FillThumbnailDecoder // Share one instance across the grid.
    @Environment(\.displayScale) private var displayScale
    @State private var image: CGImage?
    @State private var failed = false

    private struct Request: Hashable {
        let file: URL
        let scale: CGFloat
    }

    var body: some View {
        Group {
            if let image {
                Image(decorative: image, scale: displayScale)
                    .resizable()
                    .scaledToFill()
            } else if failed {
                Image(systemName: "photo.badge.exclamationmark")
                    .accessibilityLabel("Photo preview unavailable")
            } else {
                ProgressView()
            }
        }
        .frame(width: 160, height: 160)
        .clipped()
        .task(id: Request(file: file, scale: displayScale)) {
            image = nil
            failed = false
            do {
                let result = try await decoder.decode(
                    file: file, pointSize: CGSize(width: 160, height: 160),
                    displayScale: displayScale
                )
                try Task.checkCancellation()
                image = result
            } catch {
                if !Task.isCancelled { failed = true }
            }
        }
    }
}

Use a stable, app-owned file and give the view the asset’s identity in a list. If you replace the file’s contents at the same URL, include an asset revision in the task identity too. For a flexible layout, pass the actual laid-out point size into the request and include it in the task identity; don’t decode for a guessed screen width.

The image is decorative here because the surrounding row is expected to name the person or item. For a standalone meaningful photo, provide its description through an accessible label instead.

Cancellation is checked before and after decoding and before updating the view. It prevents already-cancelled work from starting and prevents a completed unwanted result from being published. It doesn’t interrupt Image I/O halfway through a synchronous decode. A large grid also needs sensible request scheduling; this actor doesn’t bound how many waiting tasks you create.

If you cache the result, include the source revision and requested pixel dimensions in the key, along with the fit/fill policy. A thumbnail made for aspect fit may be insufficient for an aspect-fill crop at the same view size.

Verify geometry separately from memory

The accompanying checks generate real image files and exercise the decoder. They compare the 480 × 360 longest-edge control with the 640 × 480 crop-aware result, check wide and tall destinations, and validate all eight JPEG orientation values with colored corners. They also cover PNG and HEIC inputs, a panorama rejected by the edge budget, a too-small source, invalid numeric requests, non-image data and cancellation before decoding.

The exact snippets compiled for iOS 17 / macOS 14 and ran on macOS 27.0.1 and iOS 27 Simulator, in both ordinary and MainActor default isolation. Older OS runtimes and physical devices were not tested.

Those are pixel and behavior checks. A 4,096-pixel edge ceiling isn’t a process-memory ceiling: decoder workspace, pixel format, other images, caches and rendering resources still contribute. Profile representative files and scrolling on your target devices before choosing the limit. We haven’t measured device peak memory or claimed an across-the-board speedup.

For a small avatar, the useful target isn’t the smallest thumbnail you can decode. It’s the smallest one that still has the pixels your chosen crop needs.