Test iOS Image Import Budgets Before Decoding
The assets transferred from Windows are only a few megabytes, yet the iOS import screen crashes when opening an image. Before changing the upload limit, remember that compressed file size is not the same as decoding cost. High-resolution still images and multiframe animations can turn a “small file” into a large number of pixels. Here, we will build a Swift preflight checker on a cloud Mac to reject inputs that exceed the budget, then test the actual decoding path.
Define four separate budgets
Split the import rules into file bytes, pixels per frame, frame count, and total pixels, and record a separate rejection reason for each. This example allows inputs of up to 20 MiB, up to 12 million pixels per frame, no more than 40 frames, and up to 48 million pixels in total. These are test-policy limits, not system recommendations.
Check width × height using the original pixel dimensions, not the dimensions in UI points. Orientation metadata changes how an image is displayed, but does not reduce its pixel count. For a typical four-channel buffer with one byte per channel, 12 million pixels require about 48 million bytes for the pixel data alone, before accounting for row alignment, color conversion, and intermediate copies.
Metadata preflight is an admission rule, not a guarantee of an upper memory limit. Even after an input passes preflight, you must handle decoding failures and limit the number of concurrent decoding tasks.
Use a conservative policy for total pixels: iterate through every frame and add up their pixel counts, without assuming that the animation player will release old frames promptly. If the product only accepts still images, setting the frame limit to one is clearer than accepting an animation and displaying only its first frame.
Build the preflight checker
Save the following file as ImageBudget.swift in your development directory on the cloud Mac. It uses system frameworks and requires no additional dependencies. The input must be a local regular file that has finished copying and will not be modified by another task. Do not keep downloading data to the same path while the check runs.
import Foundation
import ImageIO
enum ImportFailure: Error {
case rejected(String)
}
func reject(_ reason: String) throws -> Never {
throw ImportFailure.rejected(reason)
}
func inspect(_ url: URL) throws -> (frames: Int, pixels: Int) {
let values = try url.resourceValues(
forKeys: [.isRegularFileKey, .fileSizeKey]
)
guard values.isRegularFile == true,
let bytes = values.fileSize,
bytes > 0,
bytes <= 20 * 1024 * 1024 else {
try reject("file-budget")
}
let options = [
kCGImageSourceShouldCache: false
] as CFDictionary
guard let source = CGImageSourceCreateWithURL(
url as CFURL, options
) else {
try reject("unrecognized-image")
}
let count = CGImageSourceGetCount(source)
guard count > 0, count <= 40 else {
try reject("frame-budget")
}
let frameLimit = 12_000_000
let totalLimit = 48_000_000
var total = 0
for index in 0..<count {
guard let properties = CGImageSourceCopyPropertiesAtIndex(
source, index, options
) as? [CFString: Any],
let widthNumber = properties[kCGImagePropertyPixelWidth] as? NSNumber,
let heightNumber = properties[kCGImagePropertyPixelHeight] as? NSNumber
else {
try reject("missing-dimensions")
}
let width = widthNumber.intValue
let height = heightNumber.intValue
guard width > 0, height > 0,
width <= frameLimit / height else {
try reject("pixel-budget")
}
let pixels = width * height
guard pixels <= totalLimit - total else {
try reject("total-pixel-budget")
}
total += pixels
}
return (count, total)
}
do {
guard CommandLine.arguments.count == 2 else {
try reject("expected-one-file")
}
let url = URL(fileURLWithPath: CommandLine.arguments[1])
let result = try inspect(url)
print("accepted frames=\(result.frames) pixels=\(result.pixels)")
} catch {
let message = Data("rejected \(error)\n".utf8)
FileHandle.standardError.write(message)
exit(1)
}
Comparing through division before multiplying prevents overflow when calculating width × height. Checking the remaining allowance before adding prevents addition overflow. Disabling caching reduces the chance that the preflight will actively generate a decode cache; it does not mean ImageIO allocates no memory.
Run the boundary test cases
Compile first, then pass in your project’s own test files one at a time. The paths in these commands are local input arguments; replace them with actual files before running the commands.
xcrun swiftc ImageBudget.swift -o image-budget
./image-budget "$HOME/Fixtures/ordinary.jpg"
./image-budget "$HOME/Fixtures/too-many-frames.gif"
Create six fixed groups of test fixtures: a normal still image, a file that exceeds the byte limit, an image that exceeds the per-frame pixel limit, an animation that exceeds the frame limit, an animation that exceeds the total pixel limit, and damaged data. For each budget, cover both exactly at the limit and just over it. Assert that the former proceeds to subsequent processing and the latter exits with code one.
To trigger only the total pixel limit, prepare an animation with 2 million pixels per frame: 24 frames reach the example’s total limit exactly, while 25 frames exceed it without hitting the frame-count limit. Do not try to create an animation by changing a file extension. Verify that the actual container holds the required number of frames.
Include two types of damaged fixtures: files whose metadata cannot be read, and files with readable metadata but truncated pixel data. The second type may pass this script, which is precisely why the next stage must retain a failure-handling path.
Connect it to the actual import flow
When reusing the checking logic in an app, write the input to disk first, run preflight next, then decode in a background task with bounded concurrency. Do not create a full bitmap before checking its dimensions: by then, the large allocation has already happened.
If the image is only needed for a list preview, use ImageIO’s thumbnail API and set both the maximum output pixel dimension and the orientation-transform option, rather than decoding the full image and scaling it down afterward. Configure the original-image budget separately from the thumbnail-output budget. A small output is not a reason to accept unlimited input sizes.
Once an import task is canceled, it must no longer update the UI or start the next frame. Synchronous decoding calls may not respond to cancellation immediately, so you must also limit the number of tasks currently running. Processing one file at a time is a useful starting baseline; adjust it based on measurements.
Record the acceptance-test evidence
For every change, save the input file’s hash, byte count, frame count, total pixel count, decision, and rejection stage. Do not include users’ original images in public build artifacts. Use purpose-made fixtures containing no sensitive content for the regression suite.
Validate the framework logic on the cloud Mac first, then test the actual import flow in the iOS simulator and on target physical devices. Passing the desktop script does not mean peak memory usage is acceptable on a phone. Concurrent decoding, color conversion, and the UI retaining old images can all change the outcome.
Finish by checking three things: over-budget inputs never reach decoding, decoding failures do not trigger unlimited retries, and old images can be released after successive imports. Commit these assertions alongside the fixed fixtures so that the resource budget does not become an unenforced note during the next refactor.
Frequently asked questions
Does a file size limit prevent excessive decode memory use?
No. Compressed bytes do not describe decoded pixel storage. Also cap pixels per frame, frame count and total pixels, and measure peak memory in the actual decoding path.
Does passing ImageIO preflight guarantee a displayable image?
No. Preflight only admits the file to further processing. Truncated data can still fail during decoding, so handle missing results and avoid repeatedly decoding a failed input.
Move your project to a cloud Mac
Rent a dedicated physical node and access the macOS desktop in your browser. Choose your configuration and billing period, then build your project in Xcode.