Images
suggest changeThe Dart SDK has no image library. The standard choice for working with image files in Dart is package:image. It is written in pure Dart, so it works the same in command-line programs, servers, Flutter apps and the browser, with no native dependencies.
It can:
- decode PNG, JPEG, GIF (including animated), BMP, TIFF, TGA, ICO, PSD, EXR, PNM and WebP
- encode PNG, JPEG, GIF, BMP, TIFF, TGA, ICO and CUR (WebP is decode-only)
- resize, crop, rotate and flip
- apply filters: grayscale, blur, sepia, brightness, contrast and more
- draw lines, rectangles, circles and text, and composite one image onto another
- read EXIF metadata
Add it to your project:
dart pub add image
This adds a dependency like image: ^4.12.0 to pubspec.yaml. Everything in this article uses the 4.x API. Version 4 was a big rewrite, so code written for 3.x (getPixel returning an int, copyResize(img, 200) with positional arguments) won't compile.
The package exports many top-level functions with short names (fill, invert, trim), so it's common to import it with a prefix:
import 'package:image/image.dart' as img;
Creating an image and saving it
img.Image(width:, height:) creates a blank image. By default it has 3 channels (RGB) with 8 bits per channel. Pass numChannels: 4 for an alpha channel.
This program draws a gradient, writes it as PNG and JPEG, and reads the PNG back:
import 'dart:io';
import 'package:image/image.dart' as img;
Future<void> main() async {
final image = img.Image(width: 256, height: 128);
// Image is an Iterable<Pixel>, so you can loop over every pixel.
for (final p in image) {
p
..r = p.x
..g = p.y * 2
..b = 128;
}
// Encoders return the file contents as Uint8List.
final png = img.encodePng(image);
await File('gradient.png').writeAsBytes(png);
// Or encode and write in one step.
await img.encodeJpgFile('gradient.jpg', image, quality: 90);
final decoded = await img.decodeImageFile('gradient.png');
if (decoded == null) {
throw Exception('cannot decode gradient.png');
}
print('size: ${decoded.width}x${decoded.height}');
print('channels: ${decoded.numChannels}');
print('format: ${decoded.format}');
print('hasAlpha: ${decoded.hasAlpha}');
}
Output:
size: 256x128
channels: 3
format: Format.uint8
hasAlpha: false
format is the per-channel storage type (Format.uint8, Format.uint16, Format.float32, ...), not the file format. An Image in memory has no file format. You choose one when you encode it.
Decoding images
There are three ways to decode:
| Function | Use when |
|---|---|
img.decodeImage(bytes) |
You have the bytes and don't know the format. It detects the format from the data. |
img.decodePng(bytes), img.decodeJpg(bytes), ... |
You know the format. Faster, because it skips detection. |
await img.decodeImageFile(path) |
You have a file. Picks the decoder from the file extension. Not available on the web. |
All of them return null if the data isn't a valid image, so always check the result:
import 'dart:io';
import 'package:image/image.dart' as img;
img.Image loadImage(String path) {
final bytes = File(path).readAsBytesSync();
final image = img.decodeImage(bytes);
if (image == null) {
throw FormatException('not a supported image: $path');
}
return image;
}
Detecting the format
img.findFormatForData looks at the first bytes (the "magic number") and tells you what kind of image it is, without decoding the whole thing. That's useful for validating uploads, where the file name and Content-Type sent by the client can't be trusted:
import 'dart:io';
import 'package:image/image.dart' as img;
void main() {
final bytes = File('gradient.png').readAsBytesSync();
final format = img.findFormatForData(bytes);
print(format);
if (format == img.ImageFormat.invalid) {
print('not an image');
}
}
Output:
ImageFormat.png
Resizing
img.copyResize returns a new image. If you give only width or only height, the other dimension is computed to keep the aspect ratio:
import 'package:image/image.dart' as img;
void main() {
final photo = img.Image(width: 1000, height: 750);
final byWidth = img.copyResize(photo, width: 200);
print('${byWidth.width}x${byWidth.height}');
final byHeight = img.copyResize(photo, height: 300);
print('${byHeight.width}x${byHeight.height}');
// Both given: stretched to exactly this size.
final stretched = img.copyResize(photo, width: 300, height: 300);
print('${stretched.width}x${stretched.height}');
// Both given with maintainAspect: fits inside 300x300 and
// pads the rest with backgroundColor.
final padded = img.copyResize(
photo,
width: 300,
height: 300,
maintainAspect: true,
backgroundColor: img.ColorRgb8(255, 255, 255),
);
print('${padded.width}x${padded.height}');
}
Output:
200x150
400x300
300x300
300x300
Interpolation
The default interpolation is Interpolation.nearest. It is the fastest but produces jagged edges and moiré patterns when shrinking photos. For better quality, choose a different one:
final thumb = img.copyResize(
photo,
width: 200,
interpolation: img.Interpolation.average,
);
| Value | Notes |
|---|---|
nearest |
Fastest, blocky. Good for pixel art. |
linear |
Bilinear. Smooth, decent for small changes. |
cubic |
Bicubic. Sharper, good for enlarging. |
average |
Averages all source pixels covered by each target pixel. Best for downscaling photos. |
Square thumbnails
img.copyResizeCropSquare resizes so the shorter side matches size and crops the longer side around the center. It's what you want for avatars and grid thumbnails:
final avatar = img.copyResizeCropSquare(photo, size: 128);
print('${avatar.width}x${avatar.height}'); // 128x128
Cropping, rotating and flipping
import 'package:image/image.dart' as img;
void main() {
final image = img.Image(width: 400, height: 300);
// Region starting at (50, 20), 200 wide and 100 tall.
final cropped =
img.copyCrop(image, x: 50, y: 20, width: 200, height: 100);
print('cropped: ${cropped.width}x${cropped.height}');
// Rotation by 90, 180 or 270 degrees is exact.
final rotated = img.copyRotate(image, angle: 90);
print('rotated 90: ${rotated.width}x${rotated.height}');
// Other angles grow the canvas so the corners fit.
final tilted = img.copyRotate(
image,
angle: 30,
interpolation: img.Interpolation.linear,
);
print('rotated 30 is larger: ${tilted.width > image.width}');
// copyFlip returns a new image; flipHorizontal/flipVertical
// modify the image in place.
final mirrored =
img.copyFlip(image, direction: img.FlipDirection.horizontal);
img.flipVertical(image);
print('flipped: ${mirrored.width}x${mirrored.height}');
}
Output:
cropped: 200x100
rotated 90: 300x400
rotated 30 is larger: true
flipped: 400x300
A naming rule worth knowing: functions starting with copy (copyResize, copyCrop, copyRotate, copyFlip) return a new image and leave the source alone. Most other functions, including all filters and drawing functions, modify the image you pass in and return that same image for chaining. Call image.clone() first if you need to keep the original.
Fixing photo orientation with EXIF
Phone cameras usually store pixels in the sensor's orientation and record the real orientation in the EXIF Orientation tag. Viewers honor the tag, but if you resize and re-encode without looking at it, portrait photos come out sideways.
img.bakeOrientation rotates and flips the pixels to match the tag and resets the tag to "normal". The JPEG decoder already does this for you: decoding a JPEG applies the orientation and removes the tag, so for a JPEG the program below prints orientation tag: null and dimensions that are already upright. Calling bakeOrientation is harmless in that case and still needed for other formats that carry EXIF, such as TIFF:
import 'package:image/image.dart' as img;
Future<void> main() async {
final photo = await img.decodeImageFile('IMG_1234.jpg');
if (photo == null) return;
final exif = photo.exif.imageIfd;
print('orientation tag: ${exif.orientation}');
print('camera: ${exif.make} ${exif.model}');
final upright = img.bakeOrientation(photo);
print('upright: ${upright.width}x${upright.height}');
}
Do this right after decoding a photo and before any resizing or cropping. JPEG encoding keeps the EXIF data of the image by default. If you want to strip metadata such as GPS coordinates before publishing user uploads, replace it with an empty one: photo.exif = img.ExifData();.
Filters and color adjustments
Filters change the image in place:
import 'package:image/image.dart' as img;
Future<void> main() async {
final photo = await img.decodeImageFile('photo.jpg');
if (photo == null) return;
await img.encodeJpgFile(
'gray.jpg', img.grayscale(photo.clone()));
await img.encodeJpgFile(
'blur.jpg', img.gaussianBlur(photo.clone(), radius: 5));
await img.encodeJpgFile('sepia.jpg', img.sepia(photo.clone()));
await img.encodeJpgFile('negative.jpg', img.invert(photo.clone()));
final punchy = img.adjustColor(
photo.clone(),
brightness: 1.1, // 1.0 = unchanged
contrast: 1.2,
saturation: 1.3,
gamma: 0.9,
);
await img.encodeJpgFile('punchy.jpg', punchy);
}
Other useful ones are img.sobel (edge detection), img.pixelate, img.vignette, img.colorOffset, img.normalize, img.quantize (reduce the number of colors) and img.convolution for your own kernels. Most filters take an optional mask image to apply the effect only to part of the image.
Working with pixels
getPixel(x, y) returns a Pixel object. Its channels r, g, b and a are in the range of the image's format: 0-255 for uint8. rNormalized and friends give the value scaled to 0.0-1.0 regardless of format.
import 'package:image/image.dart' as img;
void main() {
final image = img.Image(width: 4, height: 4, numChannels: 4);
image.setPixelRgba(1, 2, 255, 128, 0, 255);
final p = image.getPixel(1, 2);
print('r=${p.r} g=${p.g} b=${p.b} a=${p.a}');
print('normalized g=${p.gNormalized.toStringAsFixed(3)}');
// A pixel nobody set is transparent black.
final empty = image.getPixel(0, 0);
print('r=${empty.r} a=${empty.a}');
// Count bright pixels.
var bright = 0;
for (final px in image) {
if (px.luminanceNormalized > 0.5) bright++;
}
print('bright pixels: $bright');
}
Output:
r=255 g=128 b=0 a=255
normalized g=0.502
r=0 a=0
bright pixels: 1
getPixel doesn't check bounds. Use getPixelSafe(x, y) when coordinates may be outside the image.
Raw bytes
To hand pixels to another library (a GPU texture, an ML model, Flutter's decodeImageFromPixels), get them as a flat byte list with getBytes. To go the other way, wrap existing bytes with Image.fromBytes:
import 'dart:typed_data';
import 'package:image/image.dart' as img;
void main() {
final image = img.Image(width: 2, height: 1, numChannels: 4);
image.setPixelRgba(0, 0, 10, 20, 30, 255);
image.setPixelRgba(1, 0, 40, 50, 60, 255);
final rgba = image.getBytes(order: img.ChannelOrder.rgba);
print(rgba);
final bgra = image.getBytes(order: img.ChannelOrder.bgra);
print(bgra);
final raw = Uint8List.fromList([255, 0, 0, 0, 255, 0]);
final fromRaw = img.Image.fromBytes(
width: 2,
height: 1,
bytes: raw.buffer,
numChannels: 3,
);
print(fromRaw.getPixel(1, 0).g);
}
Output:
[10, 20, 30, 255, 40, 50, 60, 255]
[30, 20, 10, 255, 60, 50, 40, 255]
255
Converting between formats
Converting a file from one format to another is decode followed by encode:
import 'package:image/image.dart' as img;
Future<void> main() async {
final image = await img.decodeImageFile('input.webp');
if (image == null) return;
// encodeImageFile picks the encoder from the extension.
await img.encodeImageFile('output.png', image);
await img.encodeJpgFile('output.jpg', image, quality: 80);
await img.encodeGifFile('output.gif', image);
}
Things to keep in mind:
- JPEG has no alpha channel. Transparent areas become black. To get a white background instead, composite onto a white image first (see below).
- JPEG quality goes from 1 to 100. The default is 100, which makes large files; 75-85 is a good range for photos.
- PNG is lossless.
encodePng(image, level: 9)compresses harder (slower, smaller); the default level is 6. - GIF supports at most 256 colors, so photos get quantized and may show banding.
- To change the channel layout, use
convert:image.convert(numChannels: 4)adds an alpha channel,image.convert(format: img.Format.uint8)turns a 16-bit PNG into 8-bit.
Drawing and compositing
Drawing functions take a Color. img.ColorRgb8(r, g, b) and img.ColorRgba8(r, g, b, a) are the most common. Text is drawn with bitmap fonts; the package includes arial14, arial24 and arial48.
import 'package:image/image.dart' as img;
Future<void> main() async {
final canvas = img.Image(width: 320, height: 200);
img.fill(canvas, color: img.ColorRgb8(255, 255, 255));
img.fillRect(canvas,
x1: 20, y1: 20, x2: 140, y2: 100,
color: img.ColorRgb8(66, 133, 244), radius: 10);
img.drawRect(canvas,
x1: 160, y1: 20, x2: 300, y2: 100,
color: img.ColorRgb8(0, 0, 0), thickness: 3);
img.fillCircle(canvas,
x: 230, y: 60, radius: 30,
color: img.ColorRgb8(234, 67, 53), antialias: true);
img.drawLine(canvas,
x1: 20, y1: 130, x2: 300, y2: 130,
color: img.ColorRgb8(52, 168, 83), thickness: 4, antialias: true);
img.drawString(canvas, 'Hello, Dart',
font: img.arial24, x: 20, y: 150,
color: img.ColorRgb8(0, 0, 0));
await img.encodePngFile('drawing.png', canvas);
}
Watermarks
img.compositeImage draws one image on top of another, blending with the source's alpha channel. Here's a semi-transparent text watermark in the bottom-right corner of a photo:
import 'package:image/image.dart' as img;
Future<void> main() async {
final photo = await img.decodeImageFile('photo.jpg');
if (photo == null) return;
// Transparent canvas for the watermark.
final mark = img.Image(width: 220, height: 40, numChannels: 4);
img.drawString(mark, '(c) example.com',
font: img.arial24, x: 5, y: 5,
color: img.ColorRgba8(255, 255, 255, 160));
img.compositeImage(photo, mark,
dstX: photo.width - mark.width - 10,
dstY: photo.height - mark.height - 10);
await img.encodeJpgFile('watermarked.jpg', photo, quality: 85);
}
The same function flattens a transparent PNG onto a solid background before saving it as JPEG:
img.Image flatten(img.Image src, img.Color background) {
final out = img.Image(width: src.width, height: src.height);
img.fill(out, color: background);
img.compositeImage(out, src);
return out;
}
// final jpg = img.encodeJpg(flatten(logo, img.ColorRgb8(255, 255, 255)));
Animated GIFs
An animated image is one Image with extra frames. image.frames lists all of them (the first is the image itself), and each frame has frameDuration in milliseconds.
import 'package:image/image.dart' as img;
Future<void> main() async {
// Build a 10-frame animation of a moving square.
final anim = img.Image(width: 100, height: 100);
for (var i = 0; i < 10; i++) {
final frame = i == 0 ? anim : img.Image(width: 100, height: 100);
img.fill(frame, color: img.ColorRgb8(255, 255, 255));
img.fillRect(frame,
x1: i * 9, y1: 40, x2: i * 9 + 20, y2: 60,
color: img.ColorRgb8(200, 0, 0));
frame.frameDuration = 100;
if (i > 0) anim.addFrame(frame);
}
await img.encodeGifFile('anim.gif', anim);
final loaded = await img.decodeImageFile('anim.gif');
print('frames: ${loaded!.numFrames}');
print('first frame delay: ${loaded.frames.first.frameDuration} ms');
// copyResize resizes every frame.
final small = img.copyResize(loaded, width: 50);
print('resized frames: ${small.numFrames}');
}
Output:
frames: 10
first frame delay: 100 ms
resized frames: 10
To get only one frame, pass frame: to the decoder, for example img.decodeGif(bytes, frame: 0). That is much faster for making a static thumbnail of a large GIF.
Performance: use another isolate
package:image is pure Dart. That makes it portable, but decoding a 12-megapixel JPEG and resizing it can take hundreds of milliseconds. In a server that blocks all other requests on the isolate; in Flutter it drops frames.
Do the work on another isolate with Isolate.run. The Uint8List result is sent back efficiently:
import 'dart:io';
import 'dart:isolate';
import 'dart:typed_data';
import 'package:image/image.dart' as img;
Uint8List makeThumbnail(Uint8List bytes, int width) {
final image = img.decodeImage(bytes);
if (image == null) throw const FormatException('not an image');
final upright = img.bakeOrientation(image);
final thumb = img.copyResize(upright,
width: width, interpolation: img.Interpolation.average);
return img.encodeJpg(thumb, quality: 80);
}
Future<void> main() async {
final bytes = await File('photo.jpg').readAsBytes();
final thumb = await Isolate.run(() => makeThumbnail(bytes, 400));
await File('photo-thumb.jpg').writeAsBytes(thumb);
print('thumbnail: ${thumb.length} bytes');
}
See Isolates for more on running code in parallel.
The Command API
The package also has a builder-style Command API that records a pipeline of operations and runs it later. executeThread() runs the whole pipeline in a separate isolate for you:
import 'package:image/image.dart' as img;
Future<void> main() async {
final cmd = img.Command()
..decodeImageFile('photo.jpg')
..bakeOrientation()
..copyResize(width: 800, interpolation: img.Interpolation.average)
..grayscale()
..writeToFile('photo-small.png'); // encoder chosen by extension
await cmd.executeThread();
final out = cmd.outputImage;
print('${out?.width}x${out?.height}');
}
Use execute() instead of executeThread() to run on the current isolate. On the web, where isolates aren't available, executeThread() falls back to running on the main thread.
Images in Flutter
In Flutter you normally display images with the Image widget, which uses the engine's fast native decoders. Reach for package:image when you need to change pixels or produce a file: resize a photo before uploading, crop an avatar, add a watermark, or generate an image. Since both Flutter and the package have a class named Image, the as img prefix avoids the clash.
To show a package:image result in a widget, encode it and use Image.memory:
final png = img.encodePng(processed);
// In build():
// Image.memory(png)
Embedding images as data URLs
To embed a small image directly in HTML, CSS or JSON, encode it and base64 it:
import 'dart:convert';
import 'package:image/image.dart' as img;
void main() {
final icon = img.Image(width: 16, height: 16);
img.fill(icon, color: img.ColorRgb8(255, 0, 0));
final dataUrl = 'data:image/png;base64,${base64Encode(img.encodePng(icon))}';
print(dataUrl.substring(0, 30));
}
Output:
data:image/png;base64,iVBORw0K
Every PNG starts with the same 8 signature bytes, which is why every PNG data URL starts with iVBORw0K. See Base64 and hex encoding for more.
Summary
| Task | Code |
|---|---|
| Decode bytes | img.decodeImage(bytes) (returns null on failure) |
| Decode file | await img.decodeImageFile(path) |
| Detect format | img.findFormatForData(bytes) |
| Encode | img.encodePng(image), img.encodeJpg(image, quality: 85) |
| Write file | await img.encodeImageFile(path, image) |
| Resize | img.copyResize(image, width: 200, interpolation: img.Interpolation.average) |
| Square thumbnail | img.copyResizeCropSquare(image, size: 128) |
| Crop | img.copyCrop(image, x: 0, y: 0, width: 100, height: 100) |
| Rotate | img.copyRotate(image, angle: 90) |
| Fix EXIF rotation | img.bakeOrientation(image) |
| Grayscale / blur | img.grayscale(image), img.gaussianBlur(image, radius: 4) |
| Overlay | img.compositeImage(dst, src, dstX: x, dstY: y) |
| Raw pixels | image.getBytes(order: img.ChannelOrder.rgba) |
| Off main isolate | await Isolate.run(() => ...) or Command().executeThread() |