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

  sdk: '>=2.10.0 <3.0.0'
  image: any
  • import dart:io and image package in the application
  • 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)));
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.

Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example

Dart| Flutter How to: Create a private variable with example