●SUBDOMAIN — Rork can now connect your web app to a subdomain only, leaving your root domain and www untouched (12/1)●UPDATES — expo-updates 58.0.23 fixes Android release builds embedding a stale runtime version●FLASH END — Intro pricing for Gemini Flash models ends 12/31, 29 days from now. Time to recheck AI feature costs●HMR — Some report the dev server picking up another server's bundle and then exiting●FIRST VIEW — Map the first screen for a normal launch, a notification, and a link, and back navigation stops surprising you●CARBON — Gemini 4 Carbon and Argon are now at standard rates: $4.00 input, $20.00 output per 1M tokens●SUBDOMAIN — Rork can now connect your web app to a subdomain only, leaving your root domain and www untouched (12/1)●UPDATES — expo-updates 58.0.23 fixes Android release builds embedding a stale runtime version●FLASH END — Intro pricing for Gemini Flash models ends 12/31, 29 days from now. Time to recheck AI feature costs●HMR — Some report the dev server picking up another server's bundle and then exiting●FIRST VIEW — Map the first screen for a normal launch, a notification, and a link, and back navigation stops surprising you●CARBON — Gemini 4 Carbon and Argon are now at standard rates: $4.00 input, $20.00 output per 1M tokens
Building an AI Photo Editor App with Rork — Filters, Background Removal, and Style Transfer in Production
Implementation notes from building an AI photo editor with Rork — non-destructive editing, background removal with fallbacks, style transfer, and picking preview resolution from device memory, with working code and the reasoning behind each call.
The Gap Between "I Want to Build a Photo App" and Actually Shipping One
Applying filters to photos, removing backgrounds with a tap, transforming snapshots into watercolor paintings — these features feel magical as a user, but overwhelming as a developer. Where do you even start? How do you handle pixel manipulation on mobile? Which background removal API actually delivers? What happens to your UI while the AI crunches for 20 seconds?
When I built this app with Rork, the first lesson hit early: image editing apps are won on UI and waiting-time design more than on algorithms. Libraries and APIs handle the heavy computation, but nobody handles the experience of waiting, the precision of undo/redo, or the feeling of control over filter intensity. Those decisions must be made before writing a single line of processing logic.
What follows is the implementation record of an AI photo editor built with Rork's prompt-based development — filters, AI background removal, style transfer, and export with sharing. Each snippet comes with the reasoning behind the call.
Ninety Seconds — The Gate That Decides Whether a Photo Editor Survives
Whether a photo editor keeps its users comes down, more than anything, to how quickly it delivers a first success after launch. By "success" I mean the whole path: launch → photo selection → one-tap filter → share candidate visible. The 90-second line is a design target I set, not a number derived from industry statistics. In your own app, put time-to-first-success and 7-day retention on the same screen and see where the curve bends.
Three things I do not skip on the first screen:
Don't trigger the photo library permission dialog right after launch. A permission request before the app has said what it is gets declined more often. Show a screen that makes the usage obvious first, and ask just before the user picks a photo. If you only need to save, iOS offers write-only access (MediaLibrary.requestPermissionsAsync(true)), so you don't need access to the whole library.
Pin the share button to a thumb-reachable spot at the bottom after a filter is applied. If it sits below the fold, the app doesn't read as "shareable." Compare share rate before and after the change, and trust your own numbers.
Within the first 30 seconds, show the user's own photo transforming. Skip the tutorial that edits someone else's picture; let a single tap change theirs.
The fork in the road for a photo editor is not the feature count. It is whether, within the first few dozen seconds, users feel "my photo just got better."
Code-Level Insight: Two-Stage Image Compression
Downsample the image to preview resolution (1080px long edge) before filtering, and replay the operations against the original only at export time. This two-stage approach keeps memory problems in check. A 12-megapixel image (4032 × 3024) occupies about 48MB once decoded (4 bytes per pixel × roughly 12.2 million pixels), and holding that full image through every operation invites background termination.
// services/image-pipeline.tsimport { ImageManipulator, SaveFormat } from 'expo-image-manipulator';// Edit operations are recorded as functions applied to a manipulator contexttype EditOp = (ctx: ReturnType<typeof ImageManipulator.manipulate>) => void;interface ImageState { originalUri: string; // never touched while editing previewUri: string; // 1080px long edge, for filter previews exportPipeline: EditOp[]; // replayed at export time}const PREVIEW_LONG_EDGE = 1080;export async function loadImageForEditing(uri: string): Promise<ImageState> { // Render with no operations to learn the original dimensions const probe = await ImageManipulator.manipulate(uri).renderAsync(); if (Math.max(probe.width, probe.height) <= PREVIEW_LONG_EDGE) { // Never upscale small images return { originalUri: uri, previewUri: uri, exportPipeline: [] }; } // Specify only the long edge; the other side follows the aspect ratio const ctx = ImageManipulator.manipulate(uri); ctx.resize( probe.width >= probe.height ? { width: PREVIEW_LONG_EDGE } : { height: PREVIEW_LONG_EDGE }, ); const preview = await (await ctx.renderAsync()).saveAsync({ compress: 0.85, format: SaveFormat.JPEG, }); return { originalUri: uri, previewUri: preview.uri, exportPipeline: [] };}export async function exportWithFullQuality( state: ImageState,): Promise<string> { // Replay every operation in one context; write the JPEG exactly once, at the end const ctx = ImageManipulator.manipulate(state.originalUri); for (const op of state.exportPipeline) op(ctx); const ref = await ctx.renderAsync(); const result = await ref.saveAsync({ compress: 0.92, format: SaveFormat.JPEG, }); return result.uri;}
The design has two benefits. Previews run on a small image, so they respond quickly. And the export writes a JPEG once; saving a JPEG after every operation loses a little quality each generation, a pattern that is common in the wild. One more trap: passing only width to resize leaves a portrait photo's long edge far above 1080px. To size by the long edge, look at the orientation and switch which side you specify.
Preview latency and crash rates vary widely by device, so I won't quote figures here. Time the filter pass with performance.now(), and watch crash rate per device model in something like Crashlytics.
✦
Thank you for reading this far.
Continue Reading
What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.
WHAT YOU'LL LEARN
✦A launch flow built around a first success within 90 seconds, plus the metrics to re-measure it in your own app
✦A two-stage pipeline: shrink for preview, write the export once at full resolution (long-edge based, new expo-image-manipulator API)
✦Choosing preview resolution from device memory, and the edge refinement that fixes cutout quality
Secure payment via Stripe · Cancel anytime
✦
Unlock This Article
Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.
Architecture Decisions — Designing the Image Processing Pipeline
The fundamental design principle for any photo editor is non-destructive editing. Rather than modifying the original image directly, you stack edit operations and maintain the ability to jump back to any previous state. Skip this decision at the start, and you'll end up rewriting the entire app when users inevitably ask for undo.
Here's the state management structure I use, generated through Rork's prompt system:
// Editor state management — non-destructive editing with undo/redo stack// Rork prompt: "Create a state manager for a photo editor with// non-destructive editing. Operations are stacked with undo/redo// support. Each operation has type, params, and timestamp."interface EditOperation { id: string; type: 'filter' | 'crop' | 'background_removal' | 'style_transfer'; params: Record<string, unknown>; timestamp: number;}interface EditorState { originalUri: string; // Never modified currentUri: string; // Currently displayed result operations: EditOperation[]; // Applied operations stack undoneOperations: EditOperation[]; // Redo stack isProcessing: boolean; processingProgress: number; // 0-100}// Undo: pop from operations, push to undoneOperations// Redo: pop from undoneOperations, push back to operations// New operation: clear undoneOperations (no branching)
Why manage undoneOperations as a separate array instead of using a state management library's time-travel feature? Because image processing ties each operation to an intermediate rendered image. General-purpose state management doesn't know about these binary assets, so you need a dedicated layer that handles both the operation metadata and the associated image files. This approach is more memory-efficient and performs better on constrained mobile hardware.
Screen Layout Strategy
Keep the navigation minimal. In my experience, layering tabs and modals inside the editor makes users lose track of which editing mode they're in.
The structure I settled on has three screens: a home screen for camera/gallery selection, an editor screen with a bottom toolbar showing four fixed tools (Filters, Background Removal, Style Transfer, Crop), and an export screen for saving and sharing.
I deliberately chose fixed icons over a scrollable toolbar. A scrollable toolbar implies hidden features, and users who don't discover them before losing patience simply leave.
Implementing Image Filters — Real-Time Preview Is Everything
Filters are the table-stakes feature, but implementation quality varies wildly. The difference between an app that makes users wait 2 seconds per filter selection and one that responds instantly is the difference between a 2-star and 5-star rating.
First, a trap in how previews get built. React Native's filter style is New Architecture only, and per the official docs only brightness and opacity work on iOS; contrast, saturate, sepia and the rest are Android-only. A preset built from a filter string therefore changes nothing in contrast, saturation or sepia on iOS. The code above draws the preview with Skia color matrices so both platforms match.
Two more implementation notes. First, use thumbnail-sized images for filter previews. Applying six different filters to a full-resolution 4000x3000 image in real time will tank the frame rate on budget Android devices. Let users pick a preset on thumbnails, then process the full-resolution image only when they tap "Apply."
Second, the choice between onValueChange (real-time) and onSlidingComplete (on release) for sliders matters more than you'd think. Some devices handle real-time slider updates smoothly while others visibly lag. So I let the preview resolution follow the device's available memory. That implementation is below.
Deriving Preview Resolution from Device Memory
Saying "adapt to the device" is easy; deciding what to actually measure is the hard part. React Native cannot read total memory directly, so I combined getTotalMemory() from react-native-device-info with the measured duration of the first filter pass.
A static device list is the obvious alternative, but every new hardware release needs an update, and any device missing from the list runs a heavier setting than it should. A self-correcting model based on measured timings needs no list to maintain.
// services/preview-resolution.tsimport DeviceInfo from 'react-native-device-info';type Tier = 'low' | 'mid' | 'high';const TIER_WIDTH: Record<Tier, number> = { low: 640, mid: 900, high: 1280,};// One filter pass slower than this drops the tier by oneconst DEGRADE_THRESHOLD_MS = 180;// Consistently faster than this raises it by oneconst UPGRADE_THRESHOLD_MS = 45;let currentTier: Tier | null = null;let fastStreak = 0;async function detectInitialTier(): Promise<Tier> { const totalBytes = await DeviceInfo.getTotalMemory(); const totalGb = totalBytes / 1024 ** 3; // Rough boundary only — tune it against your target devices if (totalGb < 3) return 'low'; if (totalGb < 6) return 'mid'; return 'high';}export async function getPreviewWidth(): Promise<number> { if (currentTier === null) { currentTier = await detectInitialTier(); } return TIER_WIDTH[currentTier];}// Feed every measured filter pass back in to self-correctexport function reportFilterDuration(ms: number): void { if (currentTier === null) return; if (ms > DEGRADE_THRESHOLD_MS) { fastStreak = 0; if (currentTier === 'high') currentTier = 'mid'; else if (currentTier === 'mid') currentTier = 'low'; return; } if (ms < UPGRADE_THRESHOLD_MS) { fastStreak += 1; // Don't promote on a single lucky pass — require eight in a row if (fastStreak >= 8) { if (currentTier === 'low') currentTier = 'mid'; else if (currentTier === 'mid') currentTier = 'high'; fastStreak = 0; } }}
Demotion happens on a single slow pass; promotion requires eight consecutive fast ones. The asymmetry is deliberate, because the cost of being wrong is asymmetric. Almost nobody notices a preview that is one tier softer. Everybody notices a slider that lags 200ms behind their finger. When in doubt, fall toward the lower tier.
Wiring reportFilterDuration in means wrapping the filter call with a performance.now() delta and passing the result. It is tempting to persist the tier to AsyncStorage, but I chose not to. The same device performs differently depending on what else is running, so re-measuring each session tracks reality better than a stored verdict.
AI Background Removal — API Selection and Fallback Architecture
Background removal is the feature that makes users feel the "AI magic." There are two implementation approaches: cloud APIs (remove.bg, Clipdrop, Photoroom) and on-device processing (TensorFlow Lite, Core ML).
I pick a hybrid: cloud API as the primary path with on-device processing as a fallback. The reasoning is straightforward — cloud APIs generally deliver better quality, especially on tricky subjects like hair and translucent objects, but you still want a minimum of functionality offline.
One dated warning. remove.bg's official API page states that from December 1, 2026, background removal moves to Leonardo.Ai (it links a "Leonardo API Migration" guide). The code below uses the remove.bg endpoint as its example, so if you ship after that date, check the successor's specification before relying on it. Keeping the service layer swappable exists for exactly this reason.
// Background removal service — cloud API with on-device fallback// Production-quality implementation with error handling and retriesinterface BackgroundRemovalResult { success: boolean; imageUri?: string; method: 'cloud' | 'ondevice' | 'failed'; error?: string; processingTimeMs: number;}const CLOUD_API_TIMEOUT_MS = 30000;const MAX_UPLOAD_BYTES = 22 * 1024 * 1024;const MAX_RETRIES = 2;const RETRY_DELAY_MS = 1000;async function removeBackground( imageUri: string, apiKey: string,): Promise<BackgroundRemovalResult> { const startTime = Date.now(); // 1. Try cloud API with retries for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { try { const result = await callCloudApi(imageUri, apiKey); return { success: true, imageUri: result.outputUri, method: 'cloud', processingTimeMs: Date.now() - startTime, }; } catch (error) { const isLastAttempt = attempt === MAX_RETRIES; const isRetryable = isRetryableError(error); if (isLastAttempt || !isRetryable) { console.warn( `Cloud API failed (attempt ${attempt + 1}/${MAX_RETRIES + 1}):`, error instanceof Error ? error.message : 'Unknown error' ); break; } // Exponential backoff await sleep(RETRY_DELAY_MS * Math.pow(2, attempt)); } } // 2. Fallback: on-device processing try { console.log('Falling back to on-device processing...'); const onDeviceResult = await processOnDevice(imageUri); return { success: true, imageUri: onDeviceResult.outputUri, method: 'ondevice', processingTimeMs: Date.now() - startTime, }; } catch (onDeviceError) { return { success: false, method: 'failed', error: onDeviceError instanceof Error ? onDeviceError.message : 'Background removal failed', processingTimeMs: Date.now() - startTime, }; }}async function callCloudApi( imageUri: string, apiKey: string,): Promise<{ outputUri: string }> { // Fetch a Blob from the local URI (sent via FormData — no Base64 needed) const response = await fetch(imageUri); const blob = await response.blob(); // Size check (remove.bg's official page lists a 22MB maximum) if (blob.size > MAX_UPLOAD_BYTES) { throw new Error('Image too large. Maximum size is 22MB.'); } const formData = new FormData(); formData.append('image_file', blob, 'image.png'); formData.append('size', 'auto'); const controller = new AbortController(); const timeoutId = setTimeout( () => controller.abort(), CLOUD_API_TIMEOUT_MS, ); try { const apiResponse = await fetch('https://api.remove.bg/v1.0/removebg', { method: 'POST', headers: { 'X-Api-Key': apiKey }, body: formData, signal: controller.signal, }); if (!apiResponse.ok) { const errorBody = await apiResponse.text().catch(() => ''); throw new ApiError( `API returned ${apiResponse.status}: ${errorBody}`, apiResponse.status, ); } const resultBlob = await apiResponse.blob(); const outputUri = await saveBlobToFile(resultBlob, 'bg_removed.png'); return { outputUri }; } finally { clearTimeout(timeoutId); }}function isRetryableError(error: unknown): boolean { if (error instanceof ApiError) { return error.statusCode === 429 || error.statusCode >= 500; } // React Native's fetch rejects with TypeError("Network request failed"). // It starts with a capital N, so a lowercase 'network' check never matches. if (error instanceof TypeError && /network/i.test(error.message)) { return true; } // The 30-second AbortController timeout is worth retrying as well if (error instanceof Error && error.name === 'AbortError') { return true; } return false;}class ApiError extends Error { constructor(message: string, public statusCode: number) { super(message); this.name = 'ApiError'; }}function sleep(ms: number): Promise<void> { return new Promise(resolve => setTimeout(resolve, ms));}
Why Retry Logic Matters More for Image APIs
First, a mistake I'm leaving on the record. I had written the network-failure check as error.message.includes('network'), but React Native's fetch rejects with Network request failed, capital N. A lowercase 'network' never matches. I assumed the retries were working until I tried airplane mode. The check now ignores case, and the AbortError from the timeout is retried too.
Image processing APIs tend to hit timeouts and rate limits more often than typical REST endpoints. You're sending and receiving large binary payloads, and the server-side inference takes real time. An app that displays "Processing failed" with no retry loses user trust instantly.
The exponential backoff (1s → 2s → 4s) specifically addresses 429 (Rate Limit) errors. Retrying at a constant interval can actually make rate limiting stricter on some API providers.
remove.bg, Clipdrop, Photoroom — What to Check When Choosing (as of October 2026)
I won't rank the three, because their terms move faster than an article can. Here are the facts I could confirm, and the points to verify yourself.
remove.bg: the official page says the first 50 API calls are free. Input images may be up to 22MB and output up to 50 megapixels, but PNG output is capped at 10 megapixels — larger transparent images must come back as WebP or ZIP. And as noted above, a move to Leonardo.Ai is scheduled for December 1, 2026
Clipdrop: ownership has moved from Stability AI to Jasper (Jasper announced the acquisition). API terms and pricing may have changed, so check the current official page before adopting it
Photoroom: focused on e-commerce product images. Whether background replacement after removal can be handled through the API is something to confirm against its current spec
Whichever you evaluate, run the same 10–20 images through each and compare the edges by eye. Include a few each of hair, semi-transparent subjects such as glass or thin fabric, and product shots. That comparison shows accuracy differences more honestly than any feature table.
The Edge of the Returned Matte Matters More Than API Accuracy
Comparisons between background removal APIs tend to fixate on accuracy. In practice, most "this cutout looks sloppy" complaints have little to do with inference quality — they come from compositing the returned transparent PNG as-is.
Two things cause it. First, the alpha edge is too hard: opacity falls from full to zero across a single pixel, so dropping the subject onto a new background produces an outline that looks cut with a blade. Second, color spill — a subject photographed against green grass keeps green in the hair fringe, which reads as a green halo the moment you place it on white.
Neither is fixed by switching APIs. Feathering the alpha lightly and desaturating only a thin edge band changes how the cutout looks. In React Native, @shopify/react-native-skia handles this post-processing.
// services/matte-refine.tsimport { Skia, TileMode, BlendMode } from '@shopify/react-native-skia';interface RefineOptions { featherSigma: number; // Skia blurs by standard deviation (sigma); scale by long edge despillStrength: number; // 0.0 – 1.0 edgeBandPx: number; // width of the band treated as "edge", in pixels}/** * Refine the edge of the transparent PNG returned by a removal API. * 1) Desaturate only a thin edge band (the interior keeps its original color) * 2) Blur the alpha to soften the hard edge */export function refineMatte( cutoutPngBytes: Uint8Array, options: RefineOptions,): Uint8Array | null { const data = Skia.Data.fromBytes(cutoutPngBytes); const image = Skia.Image.MakeImageFromEncoded(data); if (!image) return null; const width = image.width(); const height = image.height(); const surface = Skia.Surface.Make(width, height); if (!surface) return null; const canvas = surface.getCanvas(); // 1) Draw the image in its original colors canvas.drawImage(image, 0, 0); // 2) Desaturate only the edge band. // Draw a desaturated copy on a separate layer, then punch out the interior // using the alpha shrunk by the band width (DstOut); only the band remains. // The layer is composited with SrcATop so it never raises the original alpha const s = 1 - options.despillStrength; const desaturate = Skia.ColorFilter.MakeMatrix([ 0.213 + 0.787 * s, 0.715 - 0.715 * s, 0.072 - 0.072 * s, 0, 0, 0.213 - 0.213 * s, 0.715 + 0.285 * s, 0.072 - 0.072 * s, 0, 0, 0.213 - 0.213 * s, 0.715 - 0.715 * s, 0.072 + 0.928 * s, 0, 0, 0, 0, 0, 1, 0, ]); const layerPaint = Skia.Paint(); layerPaint.setBlendMode(BlendMode.SrcATop); canvas.saveLayer(layerPaint); const edgePaint = Skia.Paint(); edgePaint.setColorFilter(desaturate); canvas.drawImage(image, 0, 0, edgePaint); const cutPaint = Skia.Paint(); cutPaint.setImageFilter( Skia.ImageFilter.MakeErode(options.edgeBandPx, options.edgeBandPx, null), ); cutPaint.setBlendMode(BlendMode.DstOut); canvas.drawImage(image, 0, 0, cutPaint); canvas.restore(); // 3) Multiply by a blurred alpha with DstIn to smooth the edge. // DstIn uses only the source alpha, so the colors survive const featherPaint = Skia.Paint(); featherPaint.setImageFilter( Skia.ImageFilter.MakeBlur( options.featherSigma, options.featherSigma, TileMode.Decal, null, ), ); featherPaint.setBlendMode(BlendMode.DstIn); canvas.drawImage(image, 0, 0, featherPaint); return surface.makeImageSnapshot().encodeToBytes();}
A common mistake to avoid: if you isolate alpha with a color matrix that zeroes RGB and then draw that, the subject comes back as a black silhouette. The code above keeps the colors and applies only the alpha through a DstIn composite. Skia API names and signatures differ between versions, so check your type definitions and always inspect the edges on a real device.
Scale featherSigma with the long edge of the image. A sigma of 1.0 does nothing on a 4000px photo, and a sigma of 3.0 dissolves the subject on an 800px thumbnail. Roughly 0.05% of the long edge (2.0 at 4000px, 0.4 at 800px) is a sane starting point, adjusted by subject type. Start edgeBandPx near 0.1% of the long edge (4px at 4000px).
For despillStrength, start around 0.35 for people and 0.15 for products. Product photography is different in kind: color fidelity drives purchase decisions, so pushing despill too far turns "the cutout looks rough" into "the color doesn't match the real item." Split the value by use case rather than searching for one number.
The pass should cost little next to the API round trip, but it varies with device and image size, so time it on your own hardware. Before I migrate to a different removal API, I try refining the edge I already have.
An Edge Contact Sheet — The Same Cutout on Four Backgrounds
White alone won't tell you whether the post-processing worked. Green spill hides on white, and a pale fringe hides on black. Place the same cutout on white, black, green, and magenta, and the edge problems show up in one glance.
I read it in a fixed order: a pale fringe left on black, a stray color around the hair on green, muddy semi-transparent areas on magenta. Run the same single image through the sheet before and after switching APIs, and before and after moving the post-processing parameters. I haven't run this component in my environment, so check it against your Skia version's type definitions and on a real device.
The API returns raw material, not a finished product. Fixing the edge and the color is the app's job.
AI Style Transfer Integration — Artistic Transformation via Replicate API
Style transfer is the feature that transforms your app from "just another filter app" into "an AI photo editor." It converts user photos into watercolor paintings, oil paintings, anime illustrations, and pencil sketches using diffusion models.
The implementation uses the Replicate API, which exposes Stable Diffusion-based models for img2img (image-to-image) transformation. Model versions get replaced over time, so the code takes a version ID that you copy from the model page. For official models, you can call /v1/models/{owner}/{model}/predictions without a version. Don't treat output file URLs as permanent: save the result to the device as soon as you receive it (the retention period is covered in Replicate's data retention docs).
// AI style transfer via Replicate API// Note: in production, move this whole function to your backend (never ship the token in the app — see Pitfall 3)// Set the 64-character version ID shown on the model's Replicate page.// A string like 'latest' is not accepted.const SDXL_VERSION_ID = 'REPLACE_WITH_VERSION_ID_FROM_MODEL_PAGE';interface StyleTransferResult { success: boolean; outputUri?: string; error?: string; style: string;}const STYLE_PROMPTS: Record<string, { prompt: string; strength: number }> = { watercolor: { prompt: 'watercolor painting, soft brushstrokes, artistic, delicate colors', strength: 0.65, }, oilpainting: { prompt: 'oil painting on canvas, thick impasto brushwork, rich vibrant colors, classical art', strength: 0.70, }, anime: { prompt: 'anime style illustration, clean lines, vibrant colors, soft hand-painted backgrounds', strength: 0.60, }, sketch: { prompt: 'pencil sketch drawing, detailed linework, crosshatching, black and white', strength: 0.75, }, cyberpunk: { prompt: 'cyberpunk neon art style, glowing neon lights, futuristic, high contrast', strength: 0.55, },};async function applyStyleTransfer( imageUri: string, styleId: keyof typeof STYLE_PROMPTS, replicateApiToken: string,): Promise<StyleTransferResult> { const style = STYLE_PROMPTS[styleId]; if (!style) { return { success: false, error: `Unknown style: ${styleId}`, style: styleId }; } try { // (downscale the long edge to about 1280px before encoding) const imageBase64 = await imageToBase64(imageUri); const dataUri = `data:image/png;base64,${imageBase64}`; const createResponse = await fetch( 'https://api.replicate.com/v1/predictions', { method: 'POST', headers: { 'Authorization': `Bearer ${replicateApiToken}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ version: SDXL_VERSION_ID, input: { image: dataUri, prompt: style.prompt, prompt_strength: style.strength, num_inference_steps: 30, guidance_scale: 7.5, }, }), }, ); if (!createResponse.ok) { const errorText = await createResponse.text(); throw new Error(`Replicate API error: ${createResponse.status} ${errorText}`); } const prediction = await createResponse.json(); const result = await pollPrediction(prediction.id, replicateApiToken, 60000); if (result.status === 'succeeded' && result.output) { const outputUrl = Array.isArray(result.output) ? result.output[0] : result.output; const localUri = await downloadAndSave(outputUrl, `style_${styleId}.png`); return { success: true, outputUri: localUri, style: styleId }; } return { success: false, error: result.error || 'Style transfer failed', style: styleId, }; } catch (error) { return { success: false, error: error instanceof Error ? error.message : 'Unknown error', style: styleId, }; }}async function pollPrediction( predictionId: string, apiToken: string, timeoutMs: number,): Promise<{ status: string; output?: string | string[]; error?: string }> { const deadline = Date.now() + timeoutMs; const pollInterval = 2000; while (Date.now() < deadline) { const response = await fetch( `https://api.replicate.com/v1/predictions/${predictionId}`, { headers: { 'Authorization': `Bearer ${apiToken}` } }, ); if (!response.ok) { throw new Error(`Poll failed: ${response.status}`); } const data = await response.json(); if (['succeeded', 'failed', 'canceled'].includes(data.status)) { return data; } await sleep(pollInterval); } throw new Error('Style transfer timed out');}
The Strength Parameter Makes or Breaks the Output
prompt_strength (0.0–1.0) controls how much the original image changes. Too high and the composition falls apart; too low and the effect is barely noticeable.
As starting points, these ranges work for each style — but behavior shifts with the model and version, so confirm them on your own photos rather than hard-coding them: watercolor works best at 0.60–0.70 (preserves composition while adding brush texture), oil painting at 0.65–0.75 (needs stronger transformation for visible texture), anime at 0.55–0.65 (lower to preserve facial features), and sketch at 0.70–0.80 (line art conversion benefits from aggressive transformation).
A slider that lets users adjust strength themselves turns "the AI changed my photo too much" into "I control how much to transform."
Processing UI Design — Making Wait Times Invisible
AI processing takes time. Duration varies widely with the API, the model and the network, so feed estimatedSeconds in the code below with the median you measured yourself. How you handle these moments defines the app's perceived quality.
The progress bar intentionally stops at 90%. AI API processing times are unpredictable, and a bar that reaches 100% while the operation is still running makes users think the app froze. The deceleration curve (fast at first, slowing down) combined with the 90% cap creates the perception that things are progressing smoothly, and the final 10% snapping into place on completion feels satisfying.
Common Mistakes and Pitfalls — Know These Before You Start
Pitfall 1: Ignoring Image Memory Management
Holding multiple full-resolution images in memory simultaneously crashes Android devices with regularity. A single 4000x3000 photo consumes roughly 48MB uncompressed. Create six filter preview copies and you're at 288MB.
The fix: shrink preview images to 1080px on the long edge or less (640–1280px with the device tiers above). Only process at full resolution when the user taps "Apply." Additionally, explicitly delete temporary files when leaving the editor:
// Temp-file cleanup — delete on screen exitimport { useEffect, useRef } from 'react';import { File } from 'expo-file-system';function useImageCleanup(tempImageUris: string[]) { // Keep the latest array in a ref and delete only on unmount // (putting the array in the deps would delete on every update) const urisRef = useRef(tempImageUris); urisRef.current = tempImageUris; useEffect(() => { return () => { urisRef.current.forEach((uri) => { try { const file = new File(uri); if (file.exists) file.delete(); } catch { // Ignore deletion failures (the OS will reclaim the cache) console.warn('Failed to clean up temp image:', uri); } }); }; }, []);}
In current Expo SDKs, expo-file-system works through the File class. The old getInfoAsync and deleteAsync are deprecated and throw at runtime when imported from the main module (import them from expo-file-system/legacy if you must keep the old API).
Pitfall 2: Ignoring EXIF Orientation Data
iPhones store rotation in EXIF metadata rather than rotating the actual pixels. Skip EXIF normalization and your app will display photos sideways or upside-down:
// Normalize EXIF orientation before processingimport { ImageManipulator, SaveFormat } from 'expo-image-manipulator';async function normalizeImageOrientation(uri: string): Promise<string> { // Render with no operations, then save — the rotation is applied to the pixels const ref = await ImageManipulator.manipulate(uri).renderAsync(); const result = await ref.saveAsync({ format: SaveFormat.PNG }); return result.uri;}
Rork-generated code sometimes places API keys directly in component files. If remove.bg or Replicate tokens end up in your app bundle, they can be extracted through decompilation in minutes.
Always route through a backend (Supabase Edge Functions or Cloudflare Workers).
// WRONG: API key exposed in client codeconst result = await fetch('https://api.remove.bg/v1.0/removebg', { headers: { 'X-Api-Key': 'YOUR_API_KEY' }, // Never do this});// CORRECT: Route through your own backendconst result = await fetch('https://your-backend.workers.dev/api/remove-bg', { method: 'POST', headers: { 'Authorization': `Bearer ${userAuthToken}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ imageBase64 }),});// Backend adds the API key and forwards to remove.bg
For readability, the earlier code in this article passes apiKey as an argument. In production, move the whole call to the backend. And an endpoint with no authentication or rate limit lets anyone spend your API quota, so put user authentication and per-user limits in from day one.
Pitfall 4: Not Monitoring Free API Quota Usage
remove.bg's official page says the first 50 API calls are free. Users casually retrying "just one more time" will burn through that quota fast. You need to read the remaining balance from the response headers and tighten the feature in stages once it drops below a threshold. The implementation is below.
remove.bg returns X-Credits-Charged in the response headers and exposes the account balance through its account endpoint. I hold that number on the backend and hand the client a restriction level derived from which band the balance falls into.
// backend: quota guard on Cloudflare Workersinterface QuotaState { remaining: number; level: 'normal' | 'conserve' | 'exhausted';}const CONSERVE_THRESHOLD = 40; // below this, throttle free usersconst EXHAUSTED_THRESHOLD = 5; // below this, paid users onlyexport async function resolveQuota(kv: KVNamespace): Promise<QuotaState> { const cached = await kv.get('removebg:remaining'); const remaining = cached ? Number(cached) : await fetchRemainingFromApi(); let level: QuotaState['level'] = 'normal'; if (remaining <= EXHAUSTED_THRESHOLD) level = 'exhausted'; else if (remaining <= CONSERVE_THRESHOLD) level = 'conserve'; return { remaining, level };}// Subtract the charged amount after every call and refresh KVexport async function commitUsage( kv: KVNamespace, response: Response,): Promise<void> { const charged = Number(response.headers.get('X-Credits-Charged') ?? '1'); const current = Number((await kv.get('removebg:remaining')) ?? '0'); const next = Math.max(0, current - charged); // Short TTL so a manual top-up in the dashboard propagates on its own await kv.put('removebg:remaining', String(next), { expirationTtl: 900 });}
The point of conserve is that it does not shut anything off. Free users drop from three passes a day to one, and only exhausted restricts the feature to paying users. Skipping the intermediate stage and showing "unavailable today" tends to show up in store reviews.
One more thing: do not mirror the same quota on the client. Counters stored on device reset with a reinstall. Keep the decision on the server, and let the client do nothing but render the level it receives.
Pitfall 5: Base64 Encoding Large Images Explodes Memory
Base64 encoding inflates data by approximately 33%. A 10MB image becomes a 13.3MB string, and during encoding the original bytes and the string sit in memory together. Whenever possible, send images as multipart form data (FormData) instead — it is easier on memory. For APIs that take data URIs, such as Replicate, downscale before sending.
Export and Sharing — The Final Mile
Saving edited images to the camera roll and sharing to social media are non-negotiable features. The detail most developers miss is offering format options — PNG is required for transparent backgrounds (after background removal), while JPEG gives smaller files for everything else.
// Export with format selection, camera roll save, and shareimport * as MediaLibrary from 'expo-media-library';import * as Sharing from 'expo-sharing';import { ImageManipulator, SaveFormat } from 'expo-image-manipulator';import { File } from 'expo-file-system';interface ExportOptions { format: 'png' | 'jpeg'; quality: number; // 0.0 - 1.0 (JPEG only) maxWidth?: number; // optional resize; aspect ratio is preserved}async function exportImage( imageUri: string, options: ExportOptions,): Promise<{ savedUri: string; fileSize: number }> { // 1. Format conversion + resize const ctx = ImageManipulator.manipulate(imageUri); if (options.maxWidth) ctx.resize({ width: options.maxWidth }); const ref = await ctx.renderAsync(); const result = await ref.saveAsync({ compress: options.quality, format: options.format === 'png' ? SaveFormat.PNG : SaveFormat.JPEG, }); // 2. Save to the camera roll (saving only, so ask for write-only access) const { status } = await MediaLibrary.requestPermissionsAsync(true); if (status !== 'granted') { throw new Error('Camera roll access was not granted'); } const asset = await MediaLibrary.createAssetAsync(result.uri); // Organize into an "AI Photo Editor" album. Album lookup can fail under // write-only access, so treat the asset as saved even if this step fails try { const album = await MediaLibrary.getAlbumAsync('AI Photo Editor'); if (album) { await MediaLibrary.addAssetsToAlbumAsync([asset], album, false); } else { await MediaLibrary.createAlbumAsync('AI Photo Editor', asset, false); } } catch (e) { console.warn('Album organization skipped:', e); } const file = new File(result.uri); const fileSize = file.exists ? file.size : 0; return { savedUri: result.uri, fileSize };}async function shareImage(imageUri: string): Promise<void> { const isAvailable = await Sharing.isAvailableAsync(); if (!isAvailable) { throw new Error('Sharing is not available on this device'); } await Sharing.shareAsync(imageUri, { mimeType: imageUri.endsWith('.png') ? 'image/png' : 'image/jpeg', dialogTitle: 'Share your edit', });}
When you export a background-removed result, choose PNG. JPEG cannot hold transparency, so the cutout background gets filled with black or white.
Creating a dedicated album ("AI Photo Editor") in the camera roll is a small touch that helps users find your app's output later. Without it, edited photos disappear into the main camera roll and users forget which app created them.
Freemium Monetization Design
The most natural monetization model for an AI photo editor is a freemium hybrid with usage-based pricing for AI features:
Prices and counts below are examples of the structure, not recommendations.
Free tier: 6 basic filters + 3 background removals per day
Monthly plan (e.g. $4.99): All filters + unlimited background removal + low-resolution style transfer
Annual plan (e.g. $39.99): Everything + high-resolution style transfer + early access to new styles
Background removal and style transfer incur API costs per call, so unlimited free access isn't sustainable. Three free uses per day is a starting point: enough to experience the value, with a path to a subscription for heavy users. Set the real number from your per-call API cost and your free users' actual usage.
RevenueCat handles subscription management, receipt validation, and churn analytics in a single integration. Prompt Rork to "implement a RevenueCat subscription paywall with monthly and annual plans" to get the basic flow, then manually add the free-tier usage tracking logic.
Monetization Design — Measure the Numbers in Your Own App
The trap with photo editors is putting features behind a paywall too early. When the free experience is thin, nobody has a reason to pay; when free use makes people want a little more, the paywall becomes a natural next step.
I won't list benchmark figures here. Averages without a source mislead more than they help. Instead, here is what to measure and how to use it.
Metric
How to measure
How to use it
7-day retention
Cohort by first-launch date
Compare before and after an onboarding change to see whether the first success is landing
Subscription rate per paywall view
Tie view and purchase events to the same screen identifier
Vary placement (right before save, or when an AI quota runs out) and compare
Ad eCPM
Per placement, in your ad network dashboard
Decide whether to keep the interstitial, the rewarded video, or both
30-day revenue per user (a simple LTV)
Subscription + ad revenue divided by the install-date cohort
Subtract API cost (background removal, style transfer) to spot features that lose money
Filter applications / share rate
Events per user per day
Evidence for setting the free-tier limit
Once those are in place, these designs are worth testing:
Open AI features generously for the first 7 days only. On day 7, a prompt like "Edit last week's photos with this AI again" gives people a reason to come back. Confirm the effect with an A/B test, and check that API cost stays acceptable.
Keep two ad surfaces: an interstitial on save and a rewarded video on filter change. Show subscribers no ads. If you mix freemium with ads, track which revenue the other one cannibalizes using the table above.
Show the App Tracking Transparency (ATT) prompt once the flow is visible, not right at launch. ATT only applies if you track. If you do, put an explanatory screen first and log how the acceptance rate moves.
Photo editing is a crowded category. Work backward from your own numbers to the rank band where API cost and ad spend pay for themselves; it makes the continue-or-narrow decision faster.
If You Specialize, Where to Focus
Generic photo editors get buried. Starting fresh, I would consider one of these:
Pet photos — auto-masking dogs and cats, background replacement, breed-specific filters. A narrower subject also lets you tune style-transfer prompts more carefully.
Baby photos — noise reduction, skin-tone correction, automatic growth-record organization, with a monthly plan the family can share.
Specializing tends to ease ASO keyword competition. How much depends on the niche, so judge cost per install from your own store data.
What Comes Next — Making This App Yours
At this point, you have a working photo editor with four core features: filters, background removal, style transfer, and export. Differentiation from here depends on two choices: which styles you add, and which audience you serve.
Specialize in wedding photography with chapel and garden background replacements, and you've carved out a niche in the invitation card market. Focus on pet photos with breed detection plus style transfer, and a different path opens up.
AI image processing capabilities improve constantly. The important architectural decision is keeping your API integrations swappable. You might use remove.bg today and be moving to a service with different terms next month; remove.bg itself has announced a December 1, 2026 migration. Abstract the service layer, keep API clients loosely coupled, and switching costs stay minimal.
Today, run ten of your own photos (a person, a semi-transparent subject, a product) through a background removal API and place the results on white and black backgrounds. If the edges look off, try the refinement above before you swap APIs.
Share
Thank You for Reading
Rork Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.