Load image bytes and display it on a canvas

Flutter tips Published on

Flutter makes loading image data and drawing it onto a canvas quite straightforward.

Why Load Image Bytes?

Sometimes you need more control over how an image is displayed, like drawing it as part of a custom shape or applying special effects. Loading the image data as bytes gives you this flexibility before rendering it.

The Steps Involved

Here's the typical flow:

1. Load the Bytes

Get the raw data of your image. If it's in your app's assets, you can use rootBundle:

final ByteData data = await rootBundle.load(path);

2. Convert to Uint8List

The ByteData needs to be converted into a Uint8List.

final Uint8List bytes = data.buffer.asUint8List();

3. Decode into a ui.Image

Now, decode the bytes into an actual image object that Flutter's ui library understands.

final ui.Image image = await decodeImageFromList(bytes);

4. Draw on a Canvas

You can use a CustomPainter to draw this ui.Image onto a canvas. In the paint method, you'll use canvas.drawImageRect.

Example Custom Painter

class MyPainter extends CustomPainter {
  final ui.Image image;

  MyPainter(this.image);

  
  void paint(Canvas canvas, Size size) {
    // Define source and destination rectangles
    final srcRect = Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble());
    final dstRect = Rect.fromLTWH(0, 0, size.width, size.height);

    canvas.drawImageRect(image, srcRect, dstRect, Paint());
  }

  
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
Using the Painter

Wrap your CustomPainter in a CustomPaint widget to show it.

This process allows you to handle images flexibly for custom drawing needs within your Flutter app.

Save 3 months of work

Create your app using our 6 years of making Flutter apps and more than 50+ apps

kickstarter for flutter apps

Frequently Asked Questions

Why would I load image data as bytes in Flutter?

Loading image data as bytes gives you more control for custom drawing on a canvas, applying filters, or manipulating the image data before displaying it.

How do I load an image from assets as bytes?

You can use `rootBundle.load(path)` to load the image data from your app's assets.

How do I convert the loaded bytes into a displayable image?

You first convert the `ByteData` to `Uint8List` and then use the `decodeImageFromList()` function from `dart:ui`.

What is a CustomPainter used for?

A `CustomPainter` is used to draw custom shapes, paths, images, and other elements directly onto a canvas, giving you precise control over rendering.

Read more
You may also be interested in
Test with GoRouter navigation  blog card image
Test with GoRouter navigation
Published on 2025-05-19T07:12:03.901Z
Hexa string color extension  blog card image
Hexa string color extension
Published on 2025-05-12T09:56:47.996Z
ApparenceKit is a flutter template generator tool by Apparence.io © 2025.
All rights reserved