Dart| Flutter How to read an image from a disk and resize a file

Sometimes, We want to read an image from a disk folder and resize it and display the image.

You can use the resized image in flutter widgets to display it

This tutorial explains how to read and resize it.

How to read images in dart?

  • First import the image library as a dependency in pubspec.yaml
name: dartapp
description: >-
   dart example application.
version: 1.0.0

environment:
  sdk: '>=2.10.0 <3.0.0'
dependencies:
  image: any
  • import dart:io and image package in the applicatio

    n

  • create a File object with the given file path

  • Decode the image using file object using decodeImage, and convert to a byte in synchronous operation using the readAsBytesSync() method

  • change the image size with copyResize and returns the image object

  • File convert image object, save the object

Here is an example program for reading, resize, and outputting image

import 'dart:io' as Io;
import 'package:image/image.dart';

void main() {
  // Load a png image.
  Image image = decodeImage(new Io.File('myphoto.png').readAsBytesSync());

  Image thumbnail = copyResize(image, width: 240);

  // save as new file with new resolution
  print(new Io.File('output.png')..writeAsBytesSync(encodePng(thumbnail)));
}