One call gives a photo the edit it needs, entirely on the device.
Website: photoeditkit.org, with before/after examples of every recipe.
PhotoEditKit is a photo editing toolkit for iOS and macOS apps. It analyzes each photo (exposure, colour cast, faces, subject placement, sensor grain, and scene type) and suggests tailored edits you can present in a picker or apply instantly. It also includes the Display P3 Core Image pipeline that renders them and an editor architecture for building custom editing interfaces.
| Original | AI edit |
|---|---|
![]() |
![]() |
![]() |
![]() |
To see it in action on iOS, AutoEdit – Smart Photo Editor on the App Store is built on PhotoEditKit: select any photo and it opens directly to the AI's top edit, with alternative suggestions one tap away.
if let config = AIPostProcessingHelper.topSuggestion(for: photo, metadata: properties) {
let edited = CIImage(cgImage: photo).applyingEditConfig(config)
}- Adaptive AI suggestions. Delivers up to ten ranked looks per photo (configurable
limit) with localized titles and rendered thumbnails, or a single best edit. A
photo that is already well-balanced returns
nilrather than an unrequested style. - Targeted corrections and styles. Corrective recipes (Brighten, Lift Shadows, Recover Highlights, Warm Up, Cool Down, Clean Up) resolve exposure, cast, noise and soft-face flaws. Stylistic recipes (Vivid, Punch, Muted, Soft) apply nuanced looks dynamically calibrated to each photo, and opt-in themes (Manga, B&W, Film, Matte, Digicam) restyle it. See all recipes.
- Skin tone preservation. Safeguards facial skin hue and saturation across all recipes, keeping skin tones natural even under aggressive color moves.
- On-device preference learning. Adapts suggestions to user choices and subsequent slider tweaks, clustered by photo characteristics and scene type. How it works.
- RAW-aware. Matches the camera's in-body rendering of RAW captures and layers further looks on top.
- Complete editor architecture.
EditControllermanages image loading, GPU live previews, undo/redo history, cropping, straightening, portrait depth blur, and full-resolution export. You supply the UI;MetalImageViewrenders live previews directly on the GPU. - HDR gain map preservation. Exports preserve the iPhone's native HDR gain map.
- Live Photo support. Edits apply seamlessly across both the still image and the paired video asset, keeping the Live Photo paired on export.
- Multi-scene video restyling. The AI evaluates the opening frame and
regenerates the selected look for each subsequent scene to match ambient shifts.
Users can override adjustments at any detected keyframe, previewing changes in
real time with
VideoPreviewPlayer. Editing videos. - Editing by conversation. With Apple Intelligence,
EditAgentturns plain requests ("a bit warmer", "make it moody", "亮一点") into an edit, checks the result and corrects it, and shows a before/after the user sets or not. Apple Intelligence. - Tone style matching. Matches one photo's tonal distribution to a reference photo or collage average using luminance quantiles, without altering underlying hue or saturation.
- Private by design. Zero network requests, no remote models to download, and no user tracking. Safe for app extensions and strict offline requirements.
- Fully localized in English, Simplified Chinese, Traditional Chinese, Japanese, and Korean.
- How it fits into your app
- Examples
- Requirements
- Installation
- Quick start: let the AI edit a photo
- Edits:
EditConfig - Rendering an edit
- AI suggestions
- The recipes
- Building an editor with
EditController - Exporting with HDR
- Keeping Live Photos live
- Editing videos
- Matching a style
- Editing by conversation with Apple Intelligence
- Threading
- Localization
- Privacy
- Support
- License
PhotoEditKit powers the underlying engine—image analysis, Core Image rendering, and session state. Your app provides the source media, user interface, and storage persistence. Here is a typical editing session, call by call:
%%{init: {"themeVariables": {"actorBkg": "#0f766e", "actorBorder": "#0f766e", "actorTextColor": "#ffffff", "actorLineColor": "#14b8a6", "labelBoxBkgColor": "#0f766e", "labelBoxBorderColor": "#0f766e", "labelTextColor": "#ffffff", "loopTextColor": "#14b8a6", "activationBkgColor": "#ccfbf1", "activationBorderColor": "#0f766e"}}}%%
sequenceDiagram
box rgba(80, 140, 220, 0.15) You build
participant UI as Your editing screen
participant Src as Your EditSource
end
box rgba(120, 120, 120, 0.15) PhotoEditKit provides
participant EC as EditController
participant E as Engine
end
UI->>EC: processAI()
Note right of UI: waits until the photo has loaded
UI->>+EC: prepare(source:)
EC->>Src: loadOriginal()
Src-->>EC: full-resolution image
EC-)E: start the AI pass on its own actor
E->>Src: loadMetadata()
Src-->>E: ImageIO properties (exposure, flash)
EC->>Src: loadPreview(maxDimension:), optional
EC->>E: render the first preview
EC-->>UI: editedImage
EC->>Src: loadDepth(), optional, for portrait blur
EC-->>-UI: prepare returns
Note left of E: ranks the looks, using what this<br>user picked on similar photos
E-->>EC: suggestions
EC-->>UI: aiProcessingState = .done(result:)<br>up to ten looks (maxSuggestions) with titles and thumbnails
loop Every edit
UI->>EC: applySuggestion, previewConfig,<br>addConfig, undoConfig
EC->>E: re-render the preview
EC-->>UI: editedImage, or MetalImageView draws it
end
UI->>+EC: exportData(config:editRotation:type:quality:metadata:)
EC->>E: record the look and slider moves for learning
EC->>Src: loadFileData()
Src-->>EC: the encoded file
EC->>E: full resolution: edit, crop, rotation, vignette,<br>encoded with the file's HDR gain map and your metadata
E-->>EC: HEIC or JPEG data
EC-->>-UI: the file's data
Note right of UI: write the file, add it to Photos, share it
UI->>EC: destroy()
A RAW adds two more calls to your source: loadRawExtras while loading and
developRaw while exporting.
| Your Application Provides | PhotoEditKit Delivers |
|---|---|
An EditSource that loads image data, metadata, and optional video or depth assets |
Asynchronous loading, AI scene/tone analysis, and ranked suggestions with live thumbnails |
| The editing UI: preset picker, adjustment sliders, and control buttons | EditController managing session state, undo/redo, crop/straighten geometry, depth blur, and MetalImageView for GPU rendering |
| Persistence & sharing: saving to disk, writing to Photos, or presenting a share sheet | Full-resolution Display P3 export, HDR gain map preservation, metadata correction, and preference learning |
For a single automatic edit with no editing screen, skip EditController
and EditSource: one AIPostProcessingHelper call and one render are enough.
See the quick start.
Each photo on the left, and on the right the edit the AI suggested for it.
| Original | AI edit |
|---|---|
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
- iOS 17.6 or later, or macOS 15 or later
- For editing by conversation: iOS 26 or macOS 26, on a device with Apple Intelligence turned on. The framework links Apple's FoundationModels weakly, so it still loads on earlier systems.
- Xcode with the Swift compiler this release was built with, or a newer one.
The framework ships a Swift module interface (
.swiftinterface), enabling compatibility with newer compiler versions; older compilers cannot read it.
The API is uniform across platforms. Images use PlatformImage (UIImage on
iOS, NSImage on macOS). Because NSImage automatically applies EXIF
orientation upon loading, pass macOS images as loaded. Code examples below
reference UIImage; substitute NSImage when targeting macOS.
PhotoEditKit ships as a binary PhotoEditKit.xcframework.
In Xcode, choose File → Add Package Dependencies…, enter
https://github.com/8kdesign/PhotoEditKit
and add the PhotoEditKit library to your app target.
To declare the dependency in your own Package.swift:
.package(url: "https://github.com/8kdesign/PhotoEditKit", from: "1.0.0")Moving up from an earlier version? UPGRADING.md lists what to change in your app for each release.
- Download
PhotoEditKit.xcframework.zipfrom the latest release, unzip it and copyPhotoEditKit.xcframeworkinto your project folder. - In your app target, go to General → Frameworks, Libraries, and Embedded
Content, click +, then Add Other… → Add Files… and pick the
.xcframework. - Set it to Embed & Sign. For an app extension that also uses it, add it to the extension as Do Not Embed; the app embeds it.
If the app crashes at launch with Library not loaded: @rpath/PhotoEditKit.framework,
the framework isn't embedded. Check step 3.
import ImageIO
import PhotoEditKit
guard let source = CGImageSourceCreateWithURL(photoURL as CFURL, nil) else { return }
let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [String: Any]
// A small upright copy is all the AI needs, and much faster than full size.
let options = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceThumbnailMaxPixelSize: 512,
] as CFDictionary
guard let small = CGImageSourceCreateThumbnailAtIndex(source, 0, options) else { return }
// Off the main thread: this measures the photo.
if let config = AIPostProcessingHelper.topSuggestion(for: small, metadata: properties),
let original = CIImage(contentsOf: photoURL, options: [.applyOrientationProperty: true]) {
let edited: CIImage = original.applyingEditConfig(config)
} else {
// The photo is already good. Keep it as it is.
}metadata represents the photo's ImageIO properties
(CGImageSourceCopyPropertiesAtIndex). Although optional, passing metadata is
strongly recommended: EXIF exposure parameters (shutter speed, aperture, ISO)
allow the AI to distinguish intentionally dark compositions (such as night
streets or candlelit interiors) from underexposed captures. Without EXIF data,
low-key night scenes are more likely to be brightened.
To guarantee deterministic suggestions, provide properties from the original
file rather than re-exported copies, screenshots, or canvas exports, which
routinely strip EXIF tags. During benchmarking, missing EXIF metadata altered
the top suggestion in approximately 1 out of 7 photos. Above ~2048 px on the
long edge, image dimensions have negligible effect on suggestions(for:).
However, downscaled or recompressed copies change what Clean Up reads: JPEG
copies can show grain the original didn't have, and on a small copy a face may
be too small to judge for sharpening. So Clean Up can appear or disappear
compared with the original.
An EditConfig describes one complete edit: slider values, crop and rotation.
The AI produces them, the editor keeps a history of them, and the pipeline
renders them.
let config = EditConfig(properties: [
.exposure: 0.2,
.contrast: 0.1,
.saturation: -0.3,
.vignette: 0.4,
])Each value is an offset from neutral, so 0 (or leaving the key out)
means "unchanged", whatever the underlying filter treats as neutral. To scale
an edit up or down, multiply its values. Leave .aspectratio and .rotation
alone when you do, because half a crop isn't a gentler crop:
var properties = config.properties
for (key, value) in properties where key != .aspectratio && key != .rotation {
properties[key] = value * 0.5
}
let gentler = EditConfig(properties: properties, crop: config.crop, editRotation: config.editRotation)EditSettingType |
Range | |
|---|---|---|
.exposure |
−0.5 … 0.5 | |
.brightness |
−0.5 … 0.5 | adjusts midtones while anchoring black and white |
.contrast |
−0.5 … 0.5 | |
.blackPoint |
−1 … 1 | positive takes milky blacks to black and keeps the highlights; negative lifts black to a faded grey |
.shadow |
−1 … 1 | positive values lift shadow detail |
.highlight |
−1 … 1 | negative values recover clipped highlights; positive values push highlights up and clip them hard at white, one colour channel at a time, like an old camera sensor (a sky turns cyan before white, and no HDR headroom is kept) |
.saturation |
−1 … 1 | |
.vibrance |
−1 … 1 | boosts muted colours while protecting skin tones, neutral grays, and already-vivid hues |
.temperature |
−1 … 1 | positive is warmer, negative cooler |
.tint |
−1 … 1 | positive is more magenta, negative greener |
.shadowWarmth |
−1 … 1 | warms or cools shadows and midtones while leaving highlights alone |
.sharpness |
−1 … 1 | positive sharpens; negative applies painterly smoothing |
.lofi |
0 … 1 | "Lo-Fi": the softness of an old low-resolution camera: the whole photo resolves at a fixed size whatever its own, from 6,000 px on the long edge as the slider leaves 0 down to 480 px (VGA) at 1; about 800 px (0.5 MP) at 0.8. The small frame also goes through a real JPEG save (quality 0.9 down to 0.4 at 1), so its blocks, ringing and colour bleeding are enlarged with it. Sized to the frame, so previews and saves match, and a render already smaller than that is left as it is |
.noiseReduction |
0 … 1 | |
.noise |
0 … 1 | adds an old small sensor's noise: fine speckle and coarser colour blotches, mostly in the shadows; not applied to Live Photo movies |
.vignette |
−1 … 1 | |
.boostRed .boostOrange .boostYellow .boostGreen .boostCyan .boostBlue .boostPurple .boostMagenta |
−1 … 1 | colour mixer: saturation of one colour band |
.hueRed … .hueMagenta (same eight bands) |
−1 … 1 | colour mixer: shifts hue toward adjacent color wheel neighbours (positive goes red toward orange, blue toward purple) |
.luminanceRed … .luminanceMagenta (same eight bands) |
−1 … 1 | colour mixer: lightens or darkens a band's colours, leaving greys alone |
.rotation |
−45 … 45 | degrees, straightening |
.depth |
0 … 40 | background aperture blur ("Background Blur"); available only when EditController.hasDepth |
type.getSetting() returns an EditSetting with the localized name, an SF
Symbol and the range (minValue, maxValue), which is everything you need to
build a slider.
Read a value with config.value(of: .saturation) (0 when untouched), and make
a change with setting.getEditConfig(amount), which is ready for
previewConfig and addConfig. A change made this way carries its setting, so
consecutive changes to one slider merge into a single undo step:
let saturation = EditSettingType.saturation.getSetting()
let current = editor.currentConfig.value(of: .saturation) // e.g. 0.2
editor.addConfig(saturation.getEditConfig(0.1)) // now 0.3availableEditSettings, colorMixerSettings and rotationSettings list the
settings in display order. The colour mixer has hue, saturation and luminance
for each of eight bands (ColorBand): colorMixerSettings(.hue) lists one
channel, and band.setting(.luminance) gives one band's slider. Every
parameter is exposed as an inspectable slider: suggestions carry no hidden
adjustments that your UI cannot display or modify.
Crop is config.crop, a rect in normalized coordinates, where (0, 0, 1, 1) is
the whole image. Quarter turns and flips are config.editRotation (EditRotation).
EditConfig is immutable. [config1, config2].combine() merges configs by
adding their values, the same way the editor stacks changes.
Core Image. Applies the colour and tone settings, and the vignette, but not crop or rotation:
let output: CIImage = input.applyingEditConfig(config)Settings always render in a fixed, deterministic sequence regardless of the order in which properties were modified: RAW recovery, noise reduction (and negative sharpness's smoothing) first, then white balance (temperature, tint), exposure, shadows and highlights, brightness, contrast, shadow warmth, the colour mixer, vibrance and saturation, dark guard, black point, then sharpening, and the vignette last.
When rendering a preview smaller than the photo, pass renderScale (preview
size ÷ full size). Because sharpening and noise reduction work in pixel space,
omitting the scale factor makes a downscaled preview look sharper and grainier
than the export.
Full render, including crop and rotation. Use PostProcessingHelper. Turn
the vignette off in the first step and apply it last, so it is centred on the
cropped photo rather than the original frame:
// On LogicActor
let helper = PostProcessingHelper(image: cgImage)
helper.applyEditConfig(config: config, includeVignette: false)
helper.applyRotationCropConfig(config: config)
helper.applyFullRotateAndFlip(editRotation: config.editRotation)
helper.applyVignette(config: config)
let result: CGImage? = helper.toCGImage()PostProcessingHelper.renderedEdit(of:config:rawRecovery:) is a shortcut for the
colour and tone part alone.
All AI is reached through AIPostProcessingHelper. The calls are synchronous
and take a noticeable amount of time on full-resolution photos, so run them off
the main thread (for example inside Task.detached { … }).
AIPostProcessingHelper.topSuggestion(for: cgImage, metadata: properties) -> EditConfig?Returns the edit the photo most needs, or nil when it doesn't need one. It
never crops or rotates. A copy of about 512 px on the long edge is enough, and
much faster than full resolution. A CGImage carries no orientation, so turn
it upright first.
topSuggestion differs from the lead item of suggestions(for:):
- Relevance thresholding: If the top-ranked recipe would barely change the
photo (
isTooSmall),topSuggestionreturnsnilrather than falling back to the next look down. A photo that is already well-balanced stays as it is instead of receiving an unrequested style (such as Soft). - Grain bypass: Because a downscaled copy conceals fine grain,
topSuggestiondoes not evaluate sensor noise and its edit never adds noise reduction. Usesuggestions(for:)on the full-size photo when grain correction matters.
let suggestions: [EditSuggestion] = AIPostProcessingHelper.suggestions(for: uiImage, metadata: properties)
for suggestion in suggestions {
suggestion.title // LocalizedStringResource, e.g. "Brighten"
suggestion.config // EditConfig to apply
suggestion.thumbnail // small rendered preview, ready for a picker
}Returns up to ten suggestions ranked by relevance. Customize suggestion generation using optional parameters:
maxSuggestions:Limits the maximum number of returned looks (minimum1; defaults to10). Setting a lower limit keeps the best of the same list in the same order (EditController.maxSuggestionswith the controller).offerOriginal: truePrepends an unedited Original suggestion (no edit) whenever no look improves on the photo as it is (disabled by default). WithEditController, setoffersOriginalSuggestionbeforeprocessAI(). Without it, Original is still returned on its own when no look is worth offering at all, so the list is never empty.includeThemes: trueAppends stylized themes that suit the photo (Manga, B&W, Film, Matte or Digicam) after corrections and regular styles, outside the count limit, withisThemeset (disabled by default). Themes never alter which other suggestions are offered or their order. WithEditController, setoffersThemeSuggestions.disabledLooks:Pass a set ofAILookcases (such as[.trueColor]) to suppress specific looks; subsequent best-ranked looks take their place. Supported bysuggestions(for:),EditController.disabledLooks, andtopSuggestion(for:metadata:disabledLooks:).
Pass the photo at full resolution so the grain measurement can evaluate sensor
noise accurately; its imageOrientation is honoured. Analysis takes ~0.2 s on a
12 MP photo in the simulator (allow additional time on older devices). If the
calling Task is cancelled, execution stops at the next stage and returns an
empty array; otherwise the list always holds at least one suggestion.
If you develop RAW files yourself, pass the camera's embedded preview. The AI then offers an Original suggestion that matches the camera's own rendering, and builds every other suggestion on top of it:
let raw = AIPostProcessingHelper.RawContext(cameraReference: embeddedPreview, rawRecovery: nil)
AIPostProcessingHelper.suggestions(for: develop, raw: raw, metadata: properties)The first photo after launch is the slowest: the AI models have to load, and
the GPU compiles each look's filters the first time it draws them. Call
prewarm() when your app launches to perform this initialization in the
background while the user is still choosing a photo:
@main
struct MyApp: App {
init() {
AIPostProcessingHelper.prewarm()
}
// …
}It returns at once and works in the background at low priority. Calling it
again does nothing. If a photo is opened before it finishes, that photo's
suggestions wait for one small step of it at most. On an iPhone 17, with
prewarm() at launch, the first photo's suggestions take about 0.3 s, as
later ones do.
let scene: AIScene? = AIPostProcessingHelper.classifyScene(cgImage)
scene?.title // localized name
scene?.icon // SF Symbol nameThe scenes are people, animals, food, object, indoor, city, sky,
nature and light. It returns nil when the photo couldn't be classified.
Suggestions adapt to the person using your app. When a photo is exported with
EditController.renderForExport after its suggestions were generated,
PhotoEditKit records what happened: which looks were offered, which one was
on the photo, and how far each slider was then moved from it. Later
suggestions use those records in two ways:
- Order. Looks the user picks move up the list. Looks shown above the one they picked, and the top looks when they save with none, move down.
- Values. If the user keeps adjusting a look the same way, for example lowering Vivid's saturation, that look starts closer to where they leave it.
Learning depends on the kind of photo. Each record is matched by how similar its photo is to the new one, using a summary of the analysis: brightness, contrast, colour, grain, faces and scene. Only close matches count, and nothing changes until there are a few of them. A habit on food photos doesn't change landscapes, and a change made after one look applies only to that look.
Strict bounds and safety guardrails: Learned adjustments are deliberately bounded to preserve visual quality:
- Ranking changes: A preferred look can advance only a few positions in the suggestion list (up to ±25 score points).
- Adjustment limits: Parameter values adapt by at most 15% of each slider's total range.
- Preserved guardrails: Downstream rules for skin tones, sensor grain, shadow/highlight clipping, and minimum perceptible adjustments remain strictly enforced.
- Fixed creative intent: A recipe's polarity never inverts (for example, Cool Down can relax toward neutral, but will never shift warm).
The records are used by suggestions(for:) and topSuggestion(for:). Only
renderForExport adds them, so an app that uses just the AIPostProcessingHelper
calls gets the recipes unchanged.
AIPostProcessingHelper.learnedEditCount // how many saves are recorded
AIPostProcessingHelper.resetLearnedPreferences() // forget them allConsider offering the reset in your settings screen.
Each suggestion comes from a fixed set of recipes. The AI selects only the recipes appropriate for the image, calibrates each parameter's intensity to match the photo's characteristics, and ranks the most impactful edit first. The same recipe adapts dynamically across different scenes: Vivid on a landscape leans into foliage greens, while Vivid on a night street intensifies neon lights.
There are two kinds. Corrections fix something about the photo: its exposure, its colour or its noise. Styles are a matter of taste. When a photo needs fixing, corrections come first.
| Recipe | What it does |
|---|---|
| Original | RAW photos only. Matches the camera's own rendering of the RAW, which is usually livelier than a plain develop. Every other recipe on a RAW starts from it. |
| Clean Up | Fixes the photo's quality rather than its look: reduces grain on a dark photo at night or one that is clearly overexposed, and sharpens a main face that reads soft. It doesn't set out to change tone or colour, though the skin guard may nudge a face. |
| Balance Light | RAW photos only. Opens up the shadows and brings back the highlights together, for backlit or high-contrast scenes. |
| Brighten | Lifts a photo that came out too dark. The subject's own colours are lifted a little further than the rest, through the colour mixer's luminance. |
| Deepen | The opposite of Brighten: richer blacks and more contrast for a photo that looks grey or washed out, without lightening it. |
| Recover Highlights | Brings back detail in bright areas such as a sky. Ranks lower when what's blown out is away from the subject, such as a white border or a lit window, since a JPEG has no detail left there to bring back. A RAW that still holds the detail keeps its place. |
| Lift Shadows | Opens up dark areas without brightening the rest of the photo, including a subject that's dark against a bright sky or window, such as a hand held up against a sunlit curtain. |
| Warm Up | Takes a blue or cold colour cast back to neutral. |
| Cool Down | Takes an orange or yellow colour cast back to neutral. |
| True Color | Corrects mixed-lighting contamination while defending authentic scene colors: • Open-shade cast: Warms cool, milky shadows and restores lost contrast in daylight scenes. • White neutralization: Removes subtle green or magenta casts from white surfaces without misclassifying naturally pale subjects (such as lavender ice cream in focus). • Ambient preservation: Retains intentional environmental light, such as warm interior lamps and night illumination. • Protective compensations: Restores colors altered during tint extraction—sky blues stay blue, foliage maintains vibrance, and shifted skin tones are re-anchored to natural skin hues. |
Warm Up and Cool Down correct a cast; they don't add one. A photo with balanced colour gets neither.
| Recipe | What it does |
|---|---|
| Crisp | Sharper detail with a little more contrast. |
| Punch | Stronger contrast with a moderate colour boost. Keeps the photo's warmth: it doesn't warm or cool it. Deepens a daylight blue sky. |
| Pop | Brighter and punchier at once, for a light-coloured subject in a dim room, such as a glass of juice under a lamp. The subject's own colours are lifted further than the rest of the photo. Not offered on photos with a lot of white. |
| Vivid | Richer, more saturated colour, led by the colours the photo is about. Uses vibrance for much of it, so muted colours gain the most while skin and colours that are already strong are left nearly as they were; on photos of people it uses vibrance alone. Deepens a daylight blue sky rather than oversaturating it, and turns the yellowish greens of sunlit leaves toward true green. |
| Muted | Quieter colour overall, while the main subject keeps its own. Takes out more colour the more colourful the photo is. |
| Soft | A gentle finish: low contrast and open shadows. Leaves colour alone. |
| Spotlight | Darkens the edges to draw the eye to the middle of the photo. Leaves colour alone. |
Themes restyle a photo as something else rather than improve it. They are only
offered with includeThemes: true, always after the corrections and styles.
| Theme | What it does |
|---|---|
| Manga | A hand-painted anime look: bright, open shadows, soft highlights, light cyan anime skies and clean leaf greens, and fine detail flattened into painted patches (negative .sharpness). The sky turns less cyan when hazy blue mountains or water share its colour. City, nature and sky photos in daylight only, not sunsets or night. |
| B&W | Black and white, with contrast, highlights and shadows set for the photo; a warm sunset sky is darkened as a blue filter does on film, through the colour mixer's luminance. Only offered on photos with strong contrast, or a city lit up at night. |
| Film | A print from colour negative film: muted colour (greens most of all, turned toward olive, and blues toward teal), strong contrast that follows the photo's own light, highlights rolled off, a little warmth and green tint, and a very subtle vignette. Slightly darker than the photo, but eases off on faces and on a subject that is already dark. Not offered on night or dark photos. |
| Matte | A faded print: softened blacks, gentler colour and a light vignette. Fades more on a contrasty photo, less on a flat one, and lifts deep blacks less. Not offered at night or in a dim room, on a photo with a strong warm cast, or on food. |
| Digicam | An early-2000s point-and-shoot: overexposed, more on brighter photos up to a point (at most about +0.2 exposure, and none on photos already bright), with highlights clipped hard to white the way a small sensor clipped them (.highlight +0.5), so a sky turns cyan and skin yellowish on the way to white, flat midtones with greyish, muddy blacks, a cool blue-cyan cast (coolest in the shade), thin colour apart from cyan-blue skies, a low-resolution softness (.lofi) with fine detail lightly smeared (slightly negative .sharpness), colour sensor noise (.noise), more on dim photos, and a light vignette on bright photos or a dark one on dark photos. Blacks are always lifted to a grey, most on dark and night photos, eased only on dark skin. Offered on any photo, dark and night ones included, but not for videos. |
- Faces: every recipe, corrections included, is adjusted so skin keeps a natural hue and saturation, and faces are brightened slightly without brightening the rest of the photo. A face lit by coloured light from different sides, as on a stage, is left as lit. A clearly blurred face near the middle of the frame is sharpened slightly (Clean Up sharpens it more firmly itself; Soft leaves it); no other sharpening is added unless the photo itself measures soft (Crisp). Faces smaller than about 2% of the frame count for less.
- Subject and focus: the AI works out where the subject is from faces, where the eye is drawn and what's in focus. It also finds hands, so a hand held up dark against a bright background is lifted even when it is too thin to stand out on its own. Brighten judges exposure partly by the subject. On a photo with a shallow depth of field, Brighten, Lift Shadows and Recover Highlights judge mostly by the part in focus, so a blurred dark background or blown-out bokeh counts for little.
- Grain: on a night or clearly overexposed photo, a recipe that would make grain more visible, such as a shadow lift, adds noise reduction for it. Noise reduction leaves fine texture (bark, fabric, hair) alone. A lift that the grain would make too costly is cut back, or the recipe is dropped.
- Small edits are skipped: a recipe that would barely change the photo isn't offered, so a good photo can get only a few suggestions.
- Similar looks are spread out: when two suggestions would look nearly the same, the second moves down the list.
EditController is an ObservableObject that runs a complete editing
session: it loads the photo, renders previews as edits change, keeps
undo/redo, runs the AI suggestions and renders the final export. You provide
the photo through an EditSource and build whatever UI you like on top.
EditController doesn't know about the photo library or files. It reads
everything through your EditSource. An ordinary photo needs only three
methods; the RAW and depth ones have defaults.
// `nonisolated` because the editor calls the source from its own actor, not
// the main actor that new Xcode projects give every type by default.
// `@unchecked Sendable` because the source is shared with that actor: it's
// safe here since nothing changes after `init`.
nonisolated final class FileEditSource: EditSource, @unchecked Sendable {
let data: Data
let imageSource: CGImageSource
init?(data: Data) {
guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { return nil }
self.data = data
self.imageSource = source
}
// The full-resolution photo. A UIImage's imageOrientation is honoured, so
// you don't need to redraw a photo that carries an EXIF orientation. On
// macOS, NSImage(data:) applies it already.
@LogicActor func loadOriginal() async -> EditSourceImage? {
UIImage(data: data).map { EditSourceImage(image: $0, isDevelopedRaw: false) }
}
// The ImageIO properties. The AI reads exposure information from them.
func loadMetadata() async -> [String: Any]? {
CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as? [String: Any]
}
// The encoded file, so an export can keep its HDR gain map.
func loadFileData() async -> (data: Data, orientation: CGImagePropertyOrientation)? {
(data, orientation)
}
private var orientation: CGImagePropertyOrientation {
let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as? [String: Any]
let value = properties?[kCGImagePropertyOrientation as String] as? UInt32
return value.flatMap(CGImagePropertyOrientation.init(rawValue:)) ?? .up
}
}For a RAW, implement isRaw, loadRawExtras and developRaw; for depth
(portrait blur), loadDepth and defaultBlurRadius. loadPreview(maxDimension:)
is optional too: implement it if you can make a small copy more cheaply than
shrinking the original, for example if you already have one on screen.
A portrait photo keeps its depth beside the image in the file. Read it in
loadDepth, turned upright by the orientation it was saved with:
@LogicActor func loadDepth() async -> (data: AVDepthData, orientation: Int32)? {
for type in [kCGImageAuxiliaryDataTypeDisparity, kCGImageAuxiliaryDataTypeDepth] {
guard let info = CGImageSourceCopyAuxiliaryDataInfoAtIndex(imageSource, 0, type) as? [String: Any],
let depth = try? AVDepthData(fromDictionaryRepresentation: info) else { continue }
let description = info[kCGImageAuxiliaryDataInfoDataDescription as String] as? [String: Any]
let saved = (description?["Orientation"] as? NSNumber)?.int32Value
return (depth, saved ?? Int32(orientation.rawValue))
}
return nil
}defaultBlurRadius is the blur the photo opens with. Leave it out (the default
is 0) for the photo to open as it was taken, with the blur there to add.
The editor calls your source from its own actors, so the source mustn't be tied to the main actor:
- In a project with Default Actor Isolation set to MainActor (the
default for new Xcode projects), mark the class
nonisolatedas above. Without it, Swift 5 mode warns and Swift 6 mode refuses to compile. - The source is handed to the editor's actor, so it has to be
Sendable. A class that doesn't change afterinitcan declare@unchecked Sendable; one that does needs a lock around what changes.
// On the main actor, e.g. in your view model
let editor = EditController()
// Show `editor.editedImage` (a preview-sized UIImage, NSImage on macOS) in your UI. It's set by
// the time `prepare` returns, and updates after every edit.
// Observe `editor.aiProcessingState` for suggestions.
editor.processAI() // ask for suggestions; runs once the photo has loaded
Task { await editor.prepare(source: source) }aiProcessingState moves from .pending to .loading to
.done(result: [EditSuggestion]), or to .unavailable when there are no
suggestions to offer.
By default every slider tick renders the preview into a bitmap and publishes
it as editedImage. That copies the whole preview from the GPU to the CPU and
back on every frame. For smoother sliders, have the controller hand over the
edit as an unrendered Core Image chain instead, and draw it with
MetalImageView, a SwiftUI view that renders straight into the screen's
drawable:
let editor = EditController()
editor.rendersPreviewOnGPU = true // set before `prepare`
// In your SwiftUI view:
@ObservedObject var editor: EditController
var body: some View {
if let chain = editor.previewCIImage {
MetalImageView(image: chain)
.aspectRatio(chain.extent.size, contentMode: .fit)
} else if let image = editor.editedImage {
Image(uiImage: image).resizable().scaledToFit()
}
}previewCIImageis the full preview, crop, straightening and vignette included, and is published on every change. Quarter turns and flips are left to your view; see below. It'sniluntil the photo has loaded, and alwaysnilwithrendersPreviewOnGPUoff.editedImageis still kept up to date for anything that needs a bitmap, such as a share sheet, but only once edits pause for a quarter of a second (and immediately for the first frame).- Size the view to the image's aspect ratio, as above. The image is fitted and centred; anything left over is transparent.
- For a view you zoom with a transform (
scaleEffect), passdetailScaleso it draws at more than screen resolution:MetalImageView(image: chain, detailScale: zoom > 1 ? 4 : 1). It never draws past the image's own pixels, so a large value means full resolution. iOS only; macOS ignores it. - Colour matches
editedImageand the export: the view renders with the same settings, into Display P3. - To show the original while a compare button is held, lay
sourcePreviewImageover the Metal view rather than removing it, so letting go doesn't wait for a new view's first frame.
It's a UIViewRepresentable (NSViewRepresentable on macOS). In UIKit, host
it in a UIHostingController.
The configs you pass to previewConfig and addConfig are changes, added
on top of the edit so far. addConfig(EditConfig(properties: [.exposure: 0.1]))
twice gives an exposure of 0.2.
| Call | |
|---|---|
applySuggestion(_:automatic:) |
apply an AI suggestion; nil removes it. appliedSuggestionID tells you which one is on. Pass automatic: true when your app applied it rather than the user, e.g. opening on the top suggestion, so keeping it counts for less when learning. See below for how it treats earlier edits |
previewConfig(_:) |
show a change while a slider is moving, without adding it to the history. Each call replaces the previous preview |
confirmPreviewConfig() |
commit the previewed change when the slider is released |
addConfig(_:) |
commit a change in one step |
undoConfig() / redoConfig() |
with canUndo() / canRedo(); see below for keeping buttons up to date |
historyCount |
how many steps undo can go back. To stop undo at a point (e.g. right after a suggestion was applied), read it there and allow undo only while it's larger |
hasEdits() |
whether anything has been changed |
showOriginalImage |
a flag for your UI, e.g. while a "compare" button is held. The controller doesn't swap images itself: show sourcePreviewImage while it's true |
currentConfig |
the edit as it stands. Read-only: change it through the calls above |
setAspectRatio(_:) |
switch the crop ratio and crop the photo to it, as one step. aspectRatio reads the current one |
editRotation |
the quarter turns and flip, read-only; see below |
hasDepth |
whether the photo has depth, so .depth (background blur) can be offered. Set once prepare has loaded it, just after the first preview |
CropView is a ready-made crop screen that works the way the Photos app
crops. Show it in place of the edited photo while the user crops or
straightens, and switch back when they're done:
if isCropping {
CropView(editor: editor)
} else {
// the edited photo, as in step 2
}- The crop sits centred and as large as the view allows, with the rest of the photo dimmed around it. Around the photo, your own background shows.
- Drag a corner or an edge to resize the crop; when the finger lifts, it grows back to fill the view and zooms the photo with it. Drag inside to move the photo under the crop, and pinch to zoom. On iOS, lifting one finger of a pinch carries on as a move with the other.
- It follows the edit as it is set elsewhere: the straightening (
.rotation), the quarter turns and flips, and the aspect ratio fromsetAspectRatio(_:). A resize keeps to that ratio. - Each gesture is previewed while it moves and committed as one undo step when it ends, so undo and redo work as for a slider.
- It draws
prerotatedImage, the photo with its colour and tone edits but before any cropping, so give it the room the edited photo had.
A quarter turn or a flip is a change like any other:
// Turn 90° clockwise, or flip left to right. Each tap turns or flips again.
editor.addConfig(EditConfig(properties: [:], editRotation: .ninety, actionType: .fullRotation))
editor.addConfig(EditConfig(properties: [:], editRotation: .originalFlip, actionType: .fullRotation))The previews (editedImage, previewCIImage) leave them out, so the photo
doesn't have to be rendered again when it turns: apply editRotation to the
view that shows them. A turned photo's width and height swap, so lay it out at
its turned size and rotate inside that:
let rotation = editor.editRotation
let turns = rotation.isNeedSizeChange()
photo
.frame(width: fitted.width, height: fitted.height) // its own shape
.scaleEffect(x: rotation.isFlipped() ? -1 : 1, y: 1)
.rotationEffect(.degrees(rotation.getDegree()))
.frame(width: turns ? fitted.height : fitted.width, // the turned shape
height: turns ? fitted.width : fitted.height)CropView and the export apply them themselves.
Applying a suggestion sets every colour and tone setting to the suggestion's own value, so slider changes made before it are replaced rather than added to. A second suggestion replaces the first. Crop, rotation and background blur are kept. It all goes on the history as one step: a single undo brings back the edit as it was, and applying a suggestion clears redo.
Slider changes made after a suggestion are separate steps on top of it.
Every edit, undo and redo fires the controller's objectWillChange. A SwiftUI
view that observes the controller re-reads canUndo() and canRedo()
automatically:
@ObservedObject var editor: EditController
Button("Undo") { editor.undoConfig() }.disabled(!editor.canUndo())In UIKit, subscribe to objectWillChange and read the values on the next turn
of the main run loop. objectWillChange fires just before the change, so
reading them inside the sink gives the old values:
cancellable = editor.objectWillChange
.receive(on: RunLoop.main)
.sink { [weak self] in
guard let self else { return }
undoButton.isEnabled = editor.canUndo()
redoButton.isEnabled = editor.canRedo()
}let config = editor.currentConfig
let rotation = editor.editRotation
let metadata = await source.loadMetadata()
if let data = await editor.exportData(config: config, editRotation: rotation,
type: .heic, quality: 0.9, metadata: metadata) {
// A HEIC file with the original's HDR gain map and metadata.
// Write it out, add it to Photos or share it.
}
editor.destroy() // when the editing session endstype is .jpeg or .heic; the defaults are .jpeg at 0.95. The metadata
is optional. When you pass it, it's corrected for the export: the photo is
marked upright, and the original's pixel size and colour profile are dropped
in favour of the new file's. Add your own tags, such as the TIFF software
name, before you pass it.
To encode the result yourself, call renderForExport(config:editRotation:)
instead. It returns the full-resolution CGImage and the HDR gain map, when
the original had one.
Both record the edit for learning, if the photo's suggestions were generated. Calling them twice in one session, for example to save and then share, records it once.
Photos taken on recent iPhones carry an HDR gain map. EditController.exportData
keeps it: the gain map is read from your source's loadFileData(), framed like
the edit and attached to the encoded file. When there's no gain map, or
attaching it fails, the image is encoded on its own, so you get a file either
way.
HDRGainMap is there for photos that don't go through EditController, or
when you call renderForExport and encode the result yourself:
let data = HDRGainMap.encode(rendered.image, gainMap: rendered.gainMap, type: .heic, quality: 0.9)If you then copy the data into a CGImageDestination to add metadata, call
HDRGainMap.copy(from:to:) as well, because ImageIO leaves the gain map behind
when it copies an image. HDRGainMap.read(from:orientation:) reads the gain
map out of an image file.
A Live Photo is a photo and a short movie that Photos pairs by an identifier
both carry. Hand the movie to the editor through your source, and
EditController.exportLivePhoto renders it again with the same edit (tone,
colour, crop, straightening and quarter turns) and pairs it with the photo:
final class MySource: EditSource {
// ...
// The Live Photo's movie as a file, or nil for a still photo.
func loadPairedVideo() async -> URL? { movieURL }
}
guard let export = await editor.exportLivePhoto(config: config, editRotation: rotation,
type: .heic, quality: 0.9,
metadata: await source.loadMetadata()) else { return }
let photoURL = /* write export.photo to a file */
try await PHPhotoLibrary.shared().performChanges {
let request = PHAssetCreationRequest.forAsset()
request.addResource(with: .photo, fileURL: photoURL, options: nil)
if let video = export.video {
request.addResource(with: .pairedVideo, fileURL: video, options: nil)
}
}
// Then delete photoURL and export.video.Give Photos both halves as files: it rejects a photo passed as Data
together with a movie passed as a file. export.video is nil when the source
has no movie, the movie couldn't be rendered, or the edit has a background blur
(the movie has no depth to blur by). The photo then comes without a pairing
identifier, so it saves as an ordinary photo. Every export strips the
original's identifier, because Photos rejects a photo that names a movie it
isn't saved with.
To get the movie from a PhotosPickerItem without asking for library access,
load it as a PHLivePhoto and copy out its .pairedVideo resource with
PHAssetResourceManager. Don't check the item's content types first: with the
current encoding, a Live Photo can list only its still's type.
If you encode the photo yourself, call exportLivePhotoVideo(from:config:editRotation:identifier:)
for the movie and put the same identifier in the photo's metadata with
LivePhoto.metadata(_:pairedWith:). If Photos still refuses the pair,
LivePhoto.removingPairing(from:) gives you the photo without its identifier,
so you can save it on its own.
The movie is written as SDR HEVC at the edited frame size. An HDR Live Photo's movie loses its HDR.
Videos are edited using the opening frame as an initial reference. EditController
analyzes that frame and presents tailored looks, allowing users to make
adjustments with standard photo editing controls. VideoEdit then propagates the
aesthetic across the entire video: it detects scene boundaries, re-evaluates the
chosen look for each scene's lighting, and smoothly interpolates from one scene to
the next. Custom slider adjustments are preserved across all frames, with support
for keyframe-specific overrides (Adjust at a keyframe).
guard let source = await VideoEditSource.open(movie: movieURL) else { return } // nil: no picture
let editor = EditController()
editor.configureForVideo() // before processAI()
editor.rendersPreviewOnGPU = true
editor.processAI()
Task { await editor.prepare(source: source) }
let video = VideoEdit(source: source)
video.start { [weak self] in self?.appliedSuggestion }VideoEditSource reads the movie where it is and never deletes it; use a
file you keep for the whole session. configureForVideo() leaves sharpening,
noise reduction and added noise out (each frame would be changed differently
and the video would shimmer; added noise would sit still over the moving
picture), drops the looks built on them (Crisp, Manga and
Clean Up), and has the AI read the frame for how dim the scene was, since a
video frame has no exposure metadata. Hide the sharpening, noise reduction and
Noise controls too: VideoLook.excludedSettings lists them.
start reads the whole video once in the background to find the scene
changes. The closure returns the suggestion applied when that finishes. Here
appliedSuggestion is your own lookup:
var appliedSuggestion: EditSuggestion? {
guard case .done(let suggestions) = editor.aiProcessingState else { return nil }
return suggestions.first { $0.id == editor.appliedSuggestionID }
}Whenever the applied suggestion changes, call video.match(appliedSuggestion)
so the new look is worked out for the other scenes. Looks already worked out
are kept.
VideoPreviewPlayer plays the video with the edit on every frame, and
VideoPreviewSurface shows it:
@StateObject private var preview = VideoPreviewPlayer()
@Environment(\.displayScale) private var displayScale
var body: some View {
GeometryReader { proxy in
VideoPreviewSurface(player: preview)
.aspectRatio(preview.size, contentMode: .fit)
.frame(width: proxy.size.width, height: proxy.size.height)
// Frames are decoded and edited at the size they're shown.
.onChange(of: proxy.size, initial: true) { _, size in
preview.maxPixelSize = CGSize(width: size.width * displayScale, height: size.height * displayScale)
}
}
.overlay(alignment: .bottom) { Scrubber(preview: preview, position: preview.position) }
.task { await preview.load(source.asset, look: currentLook) }
.onChange(of: editor.currentConfig) { preview.update(look: currentLook, showsOriginal: false) }
.onChange(of: editor.appliedSuggestionID) { preview.update(look: currentLook, showsOriginal: false) }
.onChange(of: video.revision) { preview.update(look: currentLook, showsOriginal: false) }
.onDisappear { preview.stop() }
}
var currentLook: VideoLook {
video.look(for: appliedSuggestion, edit: editor.currentConfig)
}
// Watches only the position, so only it updates as the video plays.
struct Scrubber: View {
let preview: VideoPreviewPlayer
@ObservedObject var position: VideoPreviewPosition
var body: some View {
Slider(value: Binding(get: { position.seconds }, set: { preview.scrub(to: $0) }),
in: 0 ... max(preview.duration, 0.01)) { preview.isScrubbing = $0 }
}
}- The player draws each frame into the surface itself, off the main thread,
and puts it on screen at the moment it's due. Nothing in your view updates
as the video plays. Only a view that observes
positionupdates, about 30 times a second. - It opens paused on the first frame.
play(),pause(),togglePlaying(), andscrub(to:)control it;isPlayinganddurationare published for your controls, andposition.secondsfor a scrubber. SetisScrubbingfor the length of a slider drag. It loops at the end. sizehas the edited frame's shape as soon asloadhas read the video, before the first frame is drawn, so the view doesn't jump.update(look:showsOriginal:)redraws the frame on screen straight away, playing or paused. PassshowsOriginal: trueto compare with the unedited video, framed as the edit is.video.revisionchanges when a look has been worked out for the rest of the video, and when the changes at a keyframe do. Until a look is worked out,look(for:edit:)gives the first frame's edit throughout; see Wait for the look.- Set
maxPixelSizeto the view's size in pixels. The video is then decoded at about that size, which is much cheaper for a 4K video. Leave it nil to decode and edit at full size. - Frames are shown in SDR, as they are exported. An HDR video is tone-mapped.
isMuted(ortoggleMuted()) silences the sound;hasAudiosays whether there is any, so a mute button can stand aside. SetisMuted = truebeforeloadto open a video silent.- On iOS, playing with the sound on switches the app to the playback audio
session, so the sound plays with the ring switch on silent, and
stop()hands it back. A muted video leaves the session alone, so other apps' audio carries on; unmuting while it plays switches then. SetmanagesAudioSession = falseto handle the session yourself.
video.keyframeTimes lists the keyframes, in seconds, once start has found
them. The first is always 0. Its edit is the editor's own, so adjust it
through EditController as usual. At any later keyframe, store the user's
changes in VideoEdit:
let suggestion = editor.appliedSuggestionID
// What the user sees at the keyframe at `time`: the look as built for that
// scene, with their own changes.
let shown = video.look(for: appliedSuggestion, edit: editor.currentConfig)
.config(at: time).properties[.exposure] ?? 0
// The user moved exposure to `newValue` (keep it within the setting's range).
var changes = video.adjustments(at: time, for: suggestion)
changes[.exposure, default: 0] += newValue - shown
video.setAdjustments(changes, at: time, for: suggestion)- A change is an amount added on top of the look at that keyframe. It fades in from the keyframe before and out to the one after, so it doesn't jump in on a cut.
- Changes are kept separately for each look. Picking another look shows that look's own changes, and picking the first again brings its changes back.
setAdjustmentsreplaces all the keyframe's changes. Settings set to 0 are dropped. A time that isn't one ofkeyframeTimes, or is the first, is ignored.adjustments(at:for:)reads one keyframe's changes back, for example to undo a drag.allAdjustments(for:)returns every keyframe's, for telling one edit from another, such as for an export cache. Undo and redo for these changes are up to your app.- Each change bumps
video.revision, so the preview code above redraws.look(for:edit:)andfinishedLook(for:edit:)include the changes, so the export has them too.
To show the user where they are, pause the player and scrub(to:) the
keyframe they picked.
Immediately after the user picks a look, VideoEdit builds it for every keyframe
in the background, which takes a moment (longer for a long video). Until it
finishes, every keyframe shows the first frame's values, so a slider at a later
keyframe would start from the wrong place. video.isWorkingOut(appliedSuggestion)
is true until then, and also before the keyframes are found. buildingLooks is
published, so a view that observes video updates when the build is done. While
it's working, show progress and keep the user on the keyframe they're on, with the
controls at later keyframes held still.
let look = await video.finishedLook(for: appliedSuggestion, edit: editor.currentConfig)
guard let rendered = await editor.exportVideo(from: source.movie, look: look) else { return }
try await PHPhotoLibrary.shared().performChanges {
PHAssetCreationRequest.forAsset().addResource(with: .video, fileURL: rendered, options: nil)
}
// Then delete `rendered`.
video.close() // and editor.destroy(), when the session endsfinishedLook waits until the look has been worked out for every scene.
The export is a temporary QuickTime file in SDR HEVC (Rec. 709), at the
edited frame size, with the video's sound and its date and location
metadata. Saving a video doesn't teach the
suggestions; only photo saves do.
To render frames in your own pipeline instead, call
EditController.editedMovieFrame(_:config:editRotation:) with
look.config(at: time) for each frame. Render the result with a
CIContext whose working colour space is extended sRGB, the space the
filters were tuned in. A context in linear light, such as the one an
AVVideoComposition uses unless you pass your own, makes contrast pivot on
a far darker grey and crushes shadows to black.
StyleMatcher makes one photo's tones match a reference photo, or the average
of several:
// On LogicActor
guard let reference = StyleMatcher.statistics(for: referenceImage),
let target = StyleMatcher.statistics(for: photo),
let transform = StyleMatcher.transform(for: target, matching: reference),
transform.isMeaningful else { return }
let matched = photo.applyingStyleTransform(transform)Use StyleMatcher.average(of:) to combine several references into one.
EditAgent lets the user edit by asking: "a bit warmer", "the sky is too
bright", "make it moody", "use the vivid look", "too much". It answers with a
short reply and a proposal: the photo as it is now beside the edited version.
Nothing changes on the photo until the user sets a proposal, so a
conversation can try several things and go back.
It runs on Apple's on-device language model (FoundationModels). PhotoEditKit doesn't bundle or download a model, and no photo or request leaves the device.
import PhotoEditKit
guard #available(iOS 26.0, macOS 26.0, *) else { return } // hide the feature
if case .unavailable(let reason) = EditAgent.availability {
showToast(reason) // e.g. "Turn on Apple Intelligence", localized
return
}availability is .unavailable when the device doesn't support Apple
Intelligence, it is turned off, or the model is still downloading. Read it
each time the user opens the feature: the model can finish downloading
while your app runs.
// One agent per conversation, on the editor the user is working in.
let agent = EditAgent(editor: editor)
agent.prepare() // starts looking at the photo while the user types
let reply = await agent.respond(to: "a bit warmer")
showMessage(reply.text) // in the request's language
if let proposal = reply.proposal {
showComparison(before: proposal.before, after: proposal.main.after)
// proposal.options: one, or subtle / medium / strong for a style
// proposal.fixes, proposal.warnings: see "What it checks" below
}Requests build on each other, so "more", "too much", "undo that" and
"actually, warmer instead" refer to the last answer. respond returns once the
proposal's images are rendered, usually within a few seconds. Disable your
send button while isResponding is true; a second request meanwhile is
ignored.
When the user picks an option:
agent.set(proposal, option: chosen) // chosen: one of proposal.optionsset puts the proposal's look on first, if it has one, then the slider
changes as one undo step. Pass applyLook: if your app applies looks its own
way, for example to keep its own undo history. isSet(_:) tells you whether
the photo already shows an option, for a "Set" button's state.
If the user edits the photo some other way while the conversation is hidden,
call syncWithEditor() when you show it again: the next request then starts
from the photo as it is.
When the conversation closes, cancel the task awaiting respond and call
cancel(). Both stop within a few hundredths of a second, rendering and model
work included.
requestTask?.cancel()
agent.cancel()| Kind of request | Examples | What happens |
|---|---|---|
| Light and colour | "brighter", "less contrast", "less blue", "it looks too green" | The setting, with the others it needs to look right |
| Parts of the photo | "open up the shadows", "bring back the bright areas", "deeper blue sky", "richer greens" | Shadows, highlights, or the sky's or leaves' colours |
| How far | "a bit warmer", "much darker" | A smaller or larger step |
| Styles | "moody", "dramatic", "dreamy", "airy", "softer", "vintage" | A fixed recipe per style, offered subtle, medium and strong |
| Looks | "use the vivid look", "apply True Color" | That recipe, as built for this photo |
| Fixes | "make it better", "fix the colours" | The AI's top suggestion, or its white-balance fix |
| Black and white | "make it black and white" | All colour taken out |
| Follow-ups | "more", "too much", "undo that" | The last change, repeated, halved or taken back |
| Questions | "what's wrong with this photo?" | An answer and no edit |
| Other tools | "crop it", "remove the person" | A short reply saying it can't |
Common phrasings in English and Chinese are read directly, so the same request always gives the same edit. The model plans anything else, and writes every reply.
The agent measures each try on a small render and corrects it until the photo
has moved as far as asked, at most maxReviews times. It judges the subject
more than the background, and on a dark photo the lit parts more than the
black around them.
It also scores each result with the same rules that rank the AI suggestions, and compares that with the photo as set:
proposal.fixes: problems the edit fixes, such as "too dark" or "colour cast".proposal.warnings: problems the edit causes that the photo didn't have, such as "blown highlights". Show these as a caution; the user decides.
Both are localized and empty when there's nothing to say. A problem the request asks for doesn't count as a warning: darker is meant to be darker.
When an edit would cause a problem, the agent first tries to avoid it. It brightens a photo with a bright sky through the midtones rather than exposure, and it holds brightness steady while it changes contrast or colour. When that isn't enough, it takes back half the step.
- Light and colour only. Cropping, rotating and removing things are for other tools; the agent says so.
- Phrasings outside the built-in table depend on the on-device model, so they can be answered differently on different tries.
- The first request on iOS 27 or macOS 27 also has the model look at the
photo, which adds a few seconds.
prepare()starts that early. - Apple Intelligence isn't offered in every region, language or device. Check
availabilityrather than assuming it.
Calls are marked with the actor they run on, and can be awaited from anywhere:
LogicActor, PhotoEditKit's own actor, for loading, rendering and export (EditController.prepare,renderForExport,PostProcessingHelpergeometry,StyleMatcher, and yourEditSource'sloadOriginal).MainActorfor everything onEditControllerthat changes the edit (addConfig,applySuggestion,undoConfig, …), and forVideoEditandVideoPreviewPlayer.exportVideoruns onLogicActor.
EditController runs its AI suggestions on a background actor of its own.
EditAgent is MainActor. It renders on LogicActor and calls the model off
the main thread, so awaiting respond doesn't block your UI.
AIPostProcessingHelper and applyingEditConfig aren't tied to an actor. Call
them from wherever suits you, just not on the main thread for full-size images.
Setting, recipe and scene names come back as LocalizedStringResource.
| Language | Code |
|---|---|
| English | en |
| Simplified Chinese | zh-Hans |
| Traditional Chinese | zh-Hant |
| Japanese | ja |
| Korean | ko |
iOS picks the framework's language to match your app's, so a language only shows up if your app is localized in it too.
PhotoEditKit makes no network requests and collects nothing. Photos, metadata and suggestions stay on the device. It doesn't download any models, so it works offline from the first launch.
The one thing it writes to disk is the record used for learning from
saves: Library/Application Support/PhotoEditKit/LearnedPreferences.json
in your app's container. It holds no photos or thumbnails, only the photo
summary numbers, look names and slider values for at most the 500 latest
saves (under 0.5 MB). It is included in device backups like the rest of your
app's data. It is deleted with your app, or straight away by
resetLearnedPreferences().
Editing by conversation
runs on Apple's on-device model; requests and photos stay on the device. It
writes one small file, Library/Application Support/PhotoEditKit/AgentPreferences.json,
holding how far this user likes each kind of change to go (one number per
setting, learned from "more", "too much" and the strength they set). It holds no
requests or photos.
Found a bug, or a photo the AI edits badly? Please open an issue. For a bad edit, attach the photo (or a copy at around 1024 px) and say which suggestion looked wrong. Real photos are what the recipes are tuned on.
If PhotoEditKit is useful in your app, a ⭐ helps other developers find it.
PhotoEditKit is free to use, including in commercial apps. It ships as a binary and is not open source: you may not modify it, reverse engineer it, or sell or redistribute it on its own. See LICENSE for the full terms.















