Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read (from disk) and resize an image, in Flutter/Dart

In Flutter/Dart, how can I perform the following 3 steps:

  1. Read an image from disk,
  2. Read its original dimensions (width and height),
  3. Resize it.

Note: I must be able to display the final result with a regular Flutter Image widget.

CLARIFICATION: I don't want to save the image, but I do want to actually resize it in memory.

like image 892
MarcG Avatar asked Apr 06 '18 22:04

MarcG


People also ask

How do I resize an image in a swing?

Image , resizing it doesn't require any additional libraries. Just do: Image newImage = yourImage. getScaledInstance(newWidth, newHeight, Image.


2 Answers

You can read image from the disk using the image.file constructor.

For more features you can use the Image library

A Dart library providing the ability to load, save and manipulate images in a variety of different file formats.

Sample from the documentation examples

Load a jpeg, resize it and save it as a png

    import 'dart:io' as Io;     import 'package:image/image.dart';     void main() {       // Read a jpeg image from file.       Image image = decodeImage(new Io.File('test.jpg').readAsBytesSync());        // Resize the image to a 120x? thumbnail (maintaining the aspect ratio).       Image thumbnail = copyResize(image, width: 120);        // Save the thumbnail as a PNG.       new Io.File('out/thumbnail-test.png')             ..writeAsBytesSync(encodePng(thumbnail));     } 
like image 165
Raouf Rahiche Avatar answered Oct 03 '22 15:10

Raouf Rahiche


To resize an image that is defined in pubspec.yaml use "BoxFit":

@override Widget build(BuildContext context) {   return (new Container(     width: 250.0,     height: 250.0,       alignment: Alignment.center,       decoration: new BoxDecoration(        image: DecorationImage(           image: AssetImage('assets/Launcher_Icon.png'),           fit: BoxFit.fill       ),     ),   )); } 

also reference how to access images: https://flutter.io/assets-and-images/

like image 24
Stephen Samonte Tan Avatar answered Oct 03 '22 16:10

Stephen Samonte Tan