Export Photos With An Explicit Color Space
A photo looks vivid in the editor and different after export. The JPEG extension tells you the compression format, but not how its RGB values should be interpreted. Losing or mislabeling the color space can change the result even when the pixel dimensions stay the same.
Choose an output color space as part of the export contract. Then render into that space and inspect the file you actually produced.
Conversion is different from relabeling
Apple’s Quartz color guide explains that component values need a color space to have meaning. Assigning an sRGB label to unchanged Display P3 component values is not a color conversion.
For a simple SDR export, draw the source CGImage into a bitmap context using the intended destination space, then encode that rendered image:
import CoreGraphics
import Foundation
import ImageIO
import UniformTypeIdentifiers
enum ExportGamut {
case sRGB, displayP3
var colorSpace: CGColorSpace {
CGColorSpace(name: self == .sRGB ? CGColorSpace.sRGB : CGColorSpace.displayP3)!
}
}
enum PhotoExportError: Error { case invalidSize, renderingFailed, encodingFailed }
func exportJPEG(_ image: CGImage, gamut: ExportGamut) throws -> Data {
guard image.width > 0, image.height > 0,
image.width <= 8_192, image.height <= 8_192
else { throw PhotoExportError.invalidSize }
guard
let context = CGContext(
data: nil, width: image.width, height: image.height,
bitsPerComponent: 8, bytesPerRow: 0, space: gamut.colorSpace,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
else { throw PhotoExportError.renderingFailed }
let rect = CGRect(x: 0, y: 0, width: image.width, height: image.height)
context.setFillColor(CGColor(gray: 1, alpha: 1))
context.fill(rect)
context.draw(image, in: rect)
guard let rendered = context.makeImage() else { throw PhotoExportError.renderingFailed }
let output = NSMutableData()
guard
let destination = CGImageDestinationCreateWithData(
output, UTType.jpeg.identifier as CFString, 1, nil)
else { throw PhotoExportError.encodingFailed }
CGImageDestinationAddImage(
destination, rendered, [kCGImageDestinationLossyCompressionQuality: 0.9] as CFDictionary)
guard CGImageDestinationFinalize(destination) else { throw PhotoExportError.encodingFailed }
return output as Data
}
This is an explicit 8-bit SDR JPEG path. It chooses a white matte for transparent pixels because JPEG does not preserve an alpha channel. Both choices belong in the product’s export behavior.
The dimension cap is illustrative. An 8192-by-8192 RGBA buffer alone can be about 256 MiB before source pixels, encoder buffers, or copies. Set a smaller workload-appropriate pixel budget and keep this rendering off the main actor in a bounded worker.
Keep the source interpretation intact
The input CGImage must still carry the correct source color space. If an earlier stage already stripped its profile or reinterpreted its pixels, selecting the right output space cannot reconstruct the intended original colors.
This helper also assumes orientation has already been applied to the pixels. A CGImage does not carry a UIImage’s separate orientation behavior. Normalize orientation in the import/rendering pipeline, then avoid copying an obsolete orientation tag onto already-rotated output.
Choose sRGB for an export contract that needs that gamut, or Display P3 when preserving that wider-gamut representation is appropriate for the receiving workflow. Converting out-of-gamut colors into sRGB necessarily involves a gamut mapping; no code can make the smaller space represent every P3 color unchanged.
Inspect the encoded image
Image I/O destinations encode the rendered CGImage. The fixture creates a synthetic Display P3 source, exports it to each output space, decodes each JPEG, and inspects the decoded image’s color-space name and dimensions.
On the host, the resulting images reported kCGColorSpaceSRGB and kCGColorSpaceDisplayP3, respectively, with the expected 32-by-32 dimensions. That verifies the output interpretation survived encoding. It is not a colorimetric accuracy measurement or a promise that every receiving app honors the profile.
Add reference patches and a color-managed comparison workflow if color fidelity is a product requirement. Looking at two thumbnails in different apps can mix export behavior with display management, tone mapping, and ambient viewing conditions.
Metadata needs its own policy
This helper creates a new image and does not blindly copy all source metadata. Decide which capture details, attribution, or other metadata should survive. Location metadata in particular should follow the user’s export expectations rather than being copied incidentally.
Do not describe this as preserving the original ICC profile byte for byte. It preserves an explicit chosen output color interpretation. Arbitrary custom profiles, wide-range floating-point pixels, HDR gain maps, and auxiliary depth data need a broader pipeline than this example.
If your editor uses Core Image, its rendering APIs can also accept an explicit output color space. Keep that choice at the final export boundary and test the actual format you deliver.
September 2026 review: both profile/dimension round-trips passed using Core Graphics and Image I/O, and the helper type-checked for iOS 17. The example does not preserve HDR, verify physical-display appearance, or benchmark large-photo memory use.