{

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 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)));
}
THE BEST NEWSLETTER ANYWHERE
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
Subscribe
You'll get a notification every time a post gets published here.





Related posts

How to iterate loop Enum in Dart | Get Enum with index in Flutter By Example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart tutorial examples/ Flutter By Examples

How to add Methods or Values to Enums in Dart | Flutter By Example

How to convert Double to Integer or Integer to double in Dart| Flutter By Example

How to: Enum to String in Dart | Print Enum name as String in Flutter By Example

Dart| Flutter How to get File name and extension with example