Sub topic 5
Resizing, quality, multiple images, and video
This chapter assumes you can call pickImage and read the returned XFile, and that the Android and iOS setup from earlier chapters is done. It covers the options that shape what the picker returns: downscaling, compression, multi-select, and video selection. It also covers the edge cases that make these options behave differently from what you might expect.
Why options matter
A modern phone camera produces photos of 12 to 50 megapixels. A single JPEG can be 3 to 10 MB. If you upload that as a profile avatar shown at 96 pixels, you waste bandwidth, memory, and time. Decoding a full-size image into a Flutter Image widget can also use tens of megabytes of RAM.
image_picker lets you shrink the image at pick time, before your code ever sees it. You do this with three optional parameters: maxWidth, maxHeight, and imageQuality.
Resizing with maxWidth and maxHeight
maxWidth and maxHeight are double values in logical pixels of the image itself, not device-independent pixels. They are upper bounds, not target sizes.
- If the image is already smaller than the bounds, it is not enlarged.
- If you pass only one bound, the other dimension is scaled to keep the aspect ratio.
- If you pass both, the image is scaled down to fit inside the box while keeping its aspect ratio. It is not cropped or stretched.
- A negative value throws an
ArgumentError.
For example, a 4000×3000 photo with maxWidth: 1000 becomes 1000×750. The same photo with maxWidth: 1000, maxHeight: 500 becomes about 667×500, because the height is the limiting side.
Compressing with imageQuality
imageQuality is an int from 0 to 100. Higher values keep more detail and produce larger files. Values outside the range throw an ArgumentError.
Two details commonly surprise people:
- Quality applies to lossy formats, in practice JPEG. A PNG is lossless, so quality does not shrink it, although resizing still does.
- On Android and iOS, passing any of the three options causes the plugin to re-encode the image and write a new file in the app's cache directory. The user's original in the gallery is untouched. If you pass none of them, you generally get the original file or a plain copy without re-encoding.
On web, support for these options depends on the plugin version. Check the changelog for your version before relying on them there.
Choosing a method
The plugin offers several picking methods. The table shows which one fits each need.
| Method | Returns | Use it for |
|---|---|---|
| `pickImage` | `XFile?` | One image from the gallery or camera |
| `pickMultiImage` | `List<XFile>` | Several images from the gallery |
| `pickVideo` | `XFile?` | One video from the gallery or camera |
| `pickMedia` | `XFile?` | One image or video, user's choice |
| `pickMultipleMedia` | `List<XFile>` | Any mix of images and videos |
The two pickMedia methods exist in recent plugin versions. Check that your pubspec.yaml constraint allows a version that includes them.
A picker service
This class wraps the common cases. It is plain Dart and can be used from any widget or state-management layer.
import 'package:image_picker/image_picker.dart';
class MediaService {
final ImagePicker _picker = ImagePicker();
/// A small square-ish avatar: bounded to 512 px and compressed.
Future<XFile?> pickAvatar() {
return _picker.pickImage(
source: ImageSource.gallery,
maxWidth: 512,
maxHeight: 512,
imageQuality: 80,
);
}
/// Several photos, each bounded to 1600 px on its longest side.
/// An empty list means the user cancelled.
Future<List<XFile>> pickPhotos({int? limit}) {
return _picker.pickMultiImage(
maxWidth: 1600,
maxHeight: 1600,
imageQuality: 85,
limit: limit,
);
}
/// Record a clip with the system camera, capped at 30 seconds.
Future<XFile?> recordClip() {
return _picker.pickVideo(
source: ImageSource.camera,
maxDuration: const Duration(seconds: 30),
);
}
/// Choose an existing video from the gallery.
Future<XFile?> chooseVideo() {
return _picker.pickVideo(source: ImageSource.gallery);
}
}Multiple images
pickMultiImage opens the gallery in multi-select mode. Note the cancellation behavior, which differs from pickImage:
pickImagereturnsnullwhen the user cancels.pickMultiImagereturns an empty list, so always checkisEmptyrather thannull.
The limit parameter caps how many items the user can select. It must be at least 2, or the call throws an ArgumentError. For a single item, use pickImage. Support for limit was added in a later plugin release, and on some Android versions the system picker cannot enforce it. If your layout assumes a maximum, trim the list in your own code too:
final List<XFile> picked = await service.pickPhotos(limit: 4);
final List<XFile> accepted = picked.take(4).toList();The resizing and quality options apply to every image in the batch. Each image is processed in turn, so a large selection with heavy re-encoding takes noticeable time. Show a progress indicator while you wait for the future.
Video
pickVideo returns an XFile that points to a video file. Keep these points in mind:
- The plugin does not compress or resize video.
maxWidth,maxHeight, andimageQualitydo not apply. A one-minute clip can be well over 100 MB. maxDurationlimits recording length whensourceisImageSource.camera. It does not trim a video chosen from the gallery. Check duration yourself if you need to enforce a limit on gallery videos.- The plugin does not generate thumbnails or play video. Use the
video_playerpackage to play it, and a separate package or a server-side step for thumbnails. - Recording from the camera needs the camera permission. On iOS it also needs
NSMicrophoneUsageDescription, as the setup chapter showed.
Because video files are large, check the size before uploading:
Future<void> checkSize(XFile file) async {
const int maxBytes = 50 * 1024 * 1024; // 50 MB
final int size = await file.length();
if (size > maxBytes) {
throw StateError('File is ${size ~/ (1024 * 1024)} MB, limit is 50 MB');
}
}XFile.length() reads file metadata without loading the contents, so it is cheap even for large videos.
Putting it together in a widget
This screen lets the user pick up to four photos and shows them in a grid. It uses Image.file, which works on Android and iOS. On web you would use Image.network(file.path) instead, as covered in the earlier chapter on XFile.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class PhotoGridScreen extends StatefulWidget {
const PhotoGridScreen({super.key});
@override
State<PhotoGridScreen> createState() => _PhotoGridScreenState();
}
class _PhotoGridScreenState extends State<PhotoGridScreen> {
final ImagePicker _picker = ImagePicker();
List<XFile> _photos = <XFile>[];
bool _busy = false;
Future<void> _pick() async {
setState(() => _busy = true);
try {
final List<XFile> result = await _picker.pickMultiImage(
maxWidth: 1200,
imageQuality: 85,
);
if (!mounted) return;
if (result.isNotEmpty) {
setState(() => _photos = result.take(4).toList());
}
} on ArgumentError catch (e) {
debugPrint('Bad picker option: $e');
} finally {
if (mounted) setState(() => _busy = false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Photos')),
body: GridView.count(
crossAxisCount: 2,
children: <Widget>[
for (final XFile photo in _photos)
Image.file(File(photo.path), fit: BoxFit.cover),
],
),
floatingActionButton: FloatingActionButton(
onPressed: _busy ? null : _pick,
child: _busy
? const CircularProgressIndicator()
: const Icon(Icons.photo_library),
),
);
}
}The mounted checks matter. The picker leaves your app for the system UI, and the widget may be gone by the time the future completes.
Common errors and gotchas
- Files look the same size after setting
imageQuality. The source is probably a PNG, or the platform returned the original. Check the file extension and size. - Aspect ratio looks wrong. Setting both
maxWidthandmaxHeightdoes not crop. If you want a square crop, use a cropping package after picking. - The cache grows. Resized copies live in a temporary directory. Copy files you want to keep to permanent storage, and do not assume cache files survive.
- EXIF orientation. Re-encoded images are normally rotated correctly. Original, unprocessed files may carry rotation only in metadata, and some upload pipelines ignore it.
- Large batches cause memory pressure. Hold
XFilereferences, not decoded bytes, and display withcacheWidthonImage.filewhen showing thumbnails.
Exercise
A user selects a 6000×4000 JPEG from the gallery. You call pickImage with maxWidth: 1500 and imageQuality: 80, and no maxHeight. What are the approximate dimensions of the returned image, and what happens to the original file in the gallery?
Show answer
The result is about 1500×1000. The height is scaled to keep the 3:2 aspect ratio because only maxWidth was given. The plugin re-encodes at quality 80 into a new file in the app's cache directory. The original in the gallery is not modified.
Exercise
Your app calls pickMultiImage and then runs if (result == null) return; to detect cancellation. Why does this check fail to detect a cancelled selection, and what should it be?
Show answer
pickMultiImage returns an empty list when the user cancels, never null. The check should be if (result.isEmpty) return;.