Device-Side Compression and Uploads
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Baseline date: 2026-10-07. A phone camera produces files that are far larger than any screen needs: a 12 to 48 megapixel photo is several megabytes, and a minute of 4K video can be hundreds of megabytes. Sending the original over a mobile connection is slow, expensive for the user and fragile. Compressing on the device first helps, but the server still has the final word, see upload pipelines.
What to do on the device, and what not to
| On the device | On the server | |
|---|---|---|
Images |
Downscale to the largest size the product needs (for example 2048 pixels on the long side), apply the EXIF rotation, and encode as JPEG or WebP at a sane quality. Convert HEIC to JPEG only if the backend cannot read HEIC. |
Validate the file, strip metadata, produce all variants and formats, compute the BlurHash, see image formats. |
Video |
Optionally transcode to a moderate resolution and bit rate, to shorten the upload. |
Always transcode to the ladder and package for streaming, see video encoding fundamentals. |
Metadata and privacy |
Strip location if the user did not intend to share it. |
Strip it again. Never rely on the client for security. |
Rules of thumb:
-
The server must never trust the client’s work: it validates and re-encodes everything. Device-side compression is an optimisation of the upload only.
-
Compress when the user is on mobile data or the file is big. A small, already compressed JPEG gains little, and each re-encode loses quality (generation loss).
-
Keep the original when the product needs it (for example a photo editor) and upload a compressed copy for previews.
-
Do not block the UI: compression takes seconds for images and minutes for video, and drains the battery.
HEIC and HEVC from iOS
iPhones capture HEIC photos and HEVC video by default. The files are small and not widely playable outside Apple platforms. Two options:
-
Ask iOS for a compatible format. Set the picker or the camera to export compatible formats (JPEG, H.264), at the cost of larger files.
PHPickerConfiguration.preferredAssetRepresentationMode = .compatibleandUIImagePickerController.videoExportPresetchoose what is delivered. See Camera, Media and Photos and AVFoundation. -
Upload HEIC and HEVC unchanged, and convert on the server. This keeps the smallest upload. The server needs a libheif and an HEVC-capable FFmpeg, which have licensing implications, see image formats and encoding and video encoding fundamentals.
Android phones record H.264 or HEVC, and many save images as JPEG, with HEIC and AVIF available on newer devices.
Compressing images
| Platform | Tool |
|---|---|
Android |
Decode with the size of the target ( |
iOS |
ImageIO thumbnails with |
React Native, Expo |
|
Flutter |
|
Use the ImageIO and ImageDecoder downsampling paths rather than decoding the full image and then scaling, which can run
out of memory on a 48-megapixel photo. See the Bitmap section of
Image loading with Coil and Glide.
Compressing video
Android: Media3 Transformer, see Media3. iOS: AVAssetExportSession
presets, see AVFoundation. Cross-platform libraries wrap those
(for example react-native-compressor). Choose H.264 at 720p as the target when you transcode on the device, which every
server-side pipeline can read. Device encoders vary in quality, so treat their output as an upload format, not as a
delivery format.
Uploading
Upload straight to object storage with a pre-signed URL from the API, as in upload pipelines. The app then tells the API that the upload is complete, or the storage event triggers processing.
Background uploads
A user will lock the phone or switch apps during a large upload. Use the platform’s background transfer service:
-
iOS. A background
URLSessionconfiguration, withuploadTask(with:fromFile:). The system continues the transfer after the app is suspended and relaunches it on completion, see AVFoundation for the code. -
Android. WorkManager with a
CoroutineWorkermarked as a long-running foreground worker (setForeground), orDownloadManagerfor downloads. WorkManager retries with backoff and survives process death. Reference: WorkManager and long-running workers. -
React Native and Expo.
expo-file-systemupload tasks with background support, orreact-native-background-upload, both of which wrap the native services.
Resumable and multipart uploads
For files of tens of megabytes or more, a dropped connection should not restart the upload from zero:
-
S3 multipart upload, Google Cloud Storage resumable uploads and Azure Blob block uploads split the file into parts that are uploaded independently and retried. The API signs one URL per part (S3) or returns a session URL (Google).
-
tus (tus.io) is an open protocol for resumable uploads with client libraries for the main platforms, for backends that do not use object storage directly.
-
Track which parts finished so the app can resume after a restart, and show real progress from the part count.
Progress and failure
Show progress from the transfer callbacks, and the server-side processing state afterwards (processing, ready,
failed) by polling or from a push notification, see
upload pipelines. Retry transient failures with
backoff, keep the compressed file until the API confirms the upload, and let the user cancel. Pre-signed URLs expire, so
ask for a new one when a retry happens after the expiry.
Worked example: one cover from the camera to the CDN
The running example continues here: a photo of 2400 by 3600 pixels (a book cover) is taken, prepared on the device,
uploaded in parts, and finally served as the variants w320, w640 and w1280 that the backend and the other client
pages use. The sequence below is the contract between the app, the API and object storage:
The app never decides what the final variants are: it sends the smallest file that still looks right, and the worker creates the 320, 640 and 1280 pixel files, the BlurHash and the cover metadata, see upload pipelines.
Image: downsample, rotate, encode
On iOS the ImageIO thumbnail API decodes straight to a target size, and applies the orientation when
kCGImageSourceCreateThumbnailWithTransform is set. This is the function that Kingfisher’s downsampling processor wraps,
and it is the right first step before encoding:
import ImageIO
import UniformTypeIdentifiers
func downsample(_ url: URL, maxPixel: Int) -> CGImage? {
let source = CGImageSourceCreateWithURL(url as CFURL, [kCGImageSourceShouldCache: false] as CFDictionary)!
let options: [CFString: Any] = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceCreateThumbnailWithTransform: true, // apply the EXIF orientation
kCGImageSourceThumbnailMaxPixelSize: maxPixel, // long side, in pixels
]
return CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary)
}
func write(_ image: CGImage, type: UTType, quality: Double, to url: URL) {
let destination = CGImageDestinationCreateWithURL(url as CFURL, type.identifier as CFString, 1, nil)!
CGImageDestinationAddImage(destination, image, [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary)
CGImageDestinationFinalize(destination)
}
A command-line Swift program with these functions was run on a macOS machine against a synthetic 2400 by 3600 cover (a gradient with 400 translucent ellipses, so the byte sizes are indicative of the method, not of photographs). The decoded sizes are exact, since they depend only on the pixel count:
Request (kCGImageSourceThumbnailMaxPixelSize) |
Decoded size | Decoded memory |
|---|---|---|
Full decode |
2400 by 3600 |
32.96 MiB |
720 (a 160 by 240 point slot at 3x) |
480 by 720 |
1.32 MiB |
1080 |
720 by 1080 |
2.97 MiB |
1920 |
1280 by 1920 |
9.38 MiB |
Encoding the three variant widths with CGImageDestination, JPEG at quality 0.8 and HEIC at quality 0.6, gave for the same
synthetic cover:
| Width | JPEG q0.8 | HEIC q0.6 |
|---|---|---|
320 |
0.05 MiB |
0.02 MiB |
640 |
0.12 MiB |
0.04 MiB |
1280 |
0.29 MiB |
0.09 MiB |
The ratio between the columns is what to take from the table, and it agrees with the usual advice: HEIC is about a third of
JPEG at a visually similar setting, but the quality scales of the two codecs are not comparable, so judge by eye or
with a metric on your own images. The ImageIO on that machine listed public.heic, public.avif and public.jpeg as
destination types. Ask CGImageDestinationCopyTypeIdentifiers() on the iOS versions that you support before relying on a
format, and keep JPEG as the fallback.
On Android the equivalent is ImageDecoder with a target size (see
Android: Coil, Glide and BlurHash) followed by Bitmap.compress.
The format constant matters: Bitmap.CompressFormat.WEBP_LOSSY and WEBP_LOSSLESS exist from API 30, and below that the
plain WEBP constant (deprecated since API 30) is the only WebP option. The call bitmap.compress(format, quality, out)
returns false when it fails, so check the result.
Computing the BlurHash on the device
A BlurHash has 4 + 2 * x * y characters for x by y components, see
the algorithm. The woltapp Swift package adds
UIImage.blurHash(numberOfComponents:), react-native-blurhash and expo-image (Image.generateBlurhashAsync) can
encode from an image on the device, and the Kotlin library offers an encoder. Encode from the downscaled image (a 100
pixel copy is plenty), never from the original. The result is a hint: the worker should recompute it, and the API should
reject a value whose length does not match its first character. A Swift decoder that applies this check was run against the
hash of the running example (LKO2?U%2Tw=w]~RBVZRi};RPxuwH): it reports 4 by 3 components (28 characters), decodes to
32 by 32 pixels with a mean colour of 208, 177, 162 (RGB), and returns nil for the same string with two characters cut
off. On the Mac used for the run, a thousand 32 by 32 decodes took about 160 ms.
Resumable uploads, step by step
Multipart services share one model, whatever the vendor: create an upload, send numbered parts, ask the service which parts it holds, and complete with the list. The part size is bounded on both sides: S3 requires at least 5 MiB for every part except the last and allows at most 10,000 parts, so a large file needs bigger parts. The part-splitting function below was run in Node 24, together with a local server that has the same four operations and fails one part with HTTP 503:
const MIB = 1024 * 1024;
export function planParts(size, partSize = 8 * MIB, minPart = 5 * MIB, maxParts = 10_000) {
const effective = Math.ceil(Math.max(partSize, minPart, Math.ceil(size / maxParts)) / MIB) * MIB; // whole MiB
const parts = [];
for (let offset = 0, n = 1; offset < size; offset += effective, n++) {
parts.push({ number: n, offset, length: Math.min(effective, size - offset) });
}
return parts;
}
export function backoff(attempt, base = 500, cap = 30_000, random = Math.random) {
return Math.round(random() * Math.min(cap, base * 2 ** attempt)); // "full jitter"
}
For a file of 52 MiB the split is six parts of 8 MiB and one of 4 MiB. For a 100 GiB file the part size grows to 11 MiB (9,310 parts), because 100 GiB divided into 10,000 parts is 10.24 MiB. The ceilings of the retry delay for attempts 0 to 7 are 500, 1000, 2000, 4000, 8000, 16000, 30000 and 30000 ms, and the jitter picks a random point below the ceiling so that many phones that lost the network at once do not retry at the same moment.
The upload loop first asks the service what it already has, which is why a resume after a crash needs no local bookkeeping beyond the upload id:
const { parts: done } = await (await fetch(`${base}/uploads/${uploadId}`)).json(); // the service is the truth
const have = new Set(done.map((p) => p.number));
for (const part of parts) {
if (have.has(part.number)) continue;
// PUT the slice; on HTTP 5xx retry with backoff(attempt), on 403 ask the API for a fresh pre-signed URL
}
The first run of the complete program was killed after three parts. The log of the two runs reads:
created upload 1c46a039, 7 parts of 8 MiB
server already has parts: []
part 1 uploaded
part 2 uploaded
part 3 uploaded
process killed
resuming upload 1c46a039
server already has parts: [1, 2, 3]
part 4 uploaded
part 5: HTTP 503, retry 1 after 250 ms
part 5 uploaded
part 6 uploaded
part 7 uploaded
completed: 7 parts, 52.0 MiB
Keep in local storage the upload id, the object key, the part size and a fingerprint of the file (size and modification
time). If the fingerprint changed, the file is a different one and the upload must restart. The pre-signed URL of a part is
requested right before its PUT, not at the start, so a long upload does not hit the expiry.
Parts on iOS and Android
A background URLSession can only upload from a file, so each part is copied into its own temporary file before its task
is created. The function below was compiled and run on a 21 MiB file, which it split into parts of 8, 8 and 5 MiB:
func writePartFile(source: URL, part: Part, into directory: URL) throws -> URL {
let handle = try FileHandle(forReadingFrom: source)
defer { try? handle.close() }
try handle.seek(toOffset: part.offset)
let data = try handle.read(upToCount: part.length) ?? Data()
let target = directory.appendingPathComponent("part-\(part.number).bin")
try data.write(to: target, options: .atomic)
return target
}
Set allowsExpensiveNetworkAccess and allowsConstrainedNetworkAccess to false on the configuration to keep large uploads
off cellular hotspots and Low Data Mode, and waitsForConnectivity to true so that a task started offline waits
instead of failing. The background session itself is only available in an app bundle, so the delegate code of
iOS video with AVFoundation is written but cannot be exercised from a
command-line tool.
On Android, WorkManager restarts the work after process death, and a worker per part (or one worker that loops over the missing parts) retries with the backoff policy of the request. The minimum backoff delay is 10 seconds:
class UploadWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
setForeground(createForegroundInfo()) // long-running: show a notification
val uploadId = inputData.getString("uploadId") ?: return Result.failure()
return try {
uploadMissingParts(uploadId) // asks the service which parts exist, then sends the rest
Result.success()
} catch (e: IOException) {
Result.retry() // the system applies the backoff
}
}
private fun createForegroundInfo(): ForegroundInfo = ForegroundInfo(
NOTIFICATION_ID, buildNotification(),
ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC, // required from Android 14
)
}
val request = OneTimeWorkRequestBuilder<UploadWorker>()
.setInputData(workDataOf("uploadId" to uploadId))
.setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.UNMETERED).build())
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 10, TimeUnit.SECONDS)
.build()
WorkManager.getInstance(context).enqueueUniqueWork("upload-$uploadId", ExistingWorkPolicy.KEEP, request)
From Android 14, a foreground service must declare a type in the manifest (dataSync for transfers), and the system limits
how long such a service may run, so a worker that lasts hours must be able to stop and resume, which the part list makes
possible. Use NetworkType.CONNECTED instead of UNMETERED when the user chose to upload on mobile data.
Choosing what to do on the device
| Situation | Compress first | Upload as is |
|---|---|---|
Wi-Fi, a photo of a few MiB |
No benefit |
Yes, the worker resizes |
Cellular, 12 megapixel or larger photo |
Downscale to 2048 pixels, encode once |
Only if the user asked for the original |
Video under 100 MiB on Wi-Fi |
Not needed |
Yes, the server transcodes |
Video of hundreds of MiB on cellular |
Transcode to 720p H.264 and warn about time and battery |
Offer it on Wi-Fi only |
Any file |
Never trust the result |
The server validates and re-encodes |
Related pages
-
Security and Operations lists what the server validates after the upload, whatever the device did.