How do I determine the width and height of an image in Flutter?

width and height of image flutter
flutter image.asset size
flutter resize image
flutter fit image to container
flutter reduce image size
flutter constrain image
scale up image flutter
flutter image fit

Assume I have declared my image in my pubspec.yaml like this:

  assets:
    - assets/kitten.jpg

And my Flutter code is this:

void main() {
  runApp(
    new Center(
      child: new Image.asset('assets/kitten.jpg'),
    ),
  );
}

Now that I have a new Image.asset(), how do I determine the width and height of that image? For example, I just want to print out the image's width and height.

(It looks like dart:ui's Image class has width and height, but not sure how to go from widget's Image to dart:ui's Image.)

Thanks!

UPDATED SOLUTION:

With the new version of flutter old solution is obsolete. Now the addListener needs an ImageStreamListener.

Widget build(BuildContext context) {
    Image image = new Image.network('https://i.stack.imgur.com/lkd0a.png');
    Completer<ui.Image> completer = new Completer<ui.Image>();
    image.image
      .resolve(new ImageConfiguration())
      .addListener(ImageStreamListener(ImageInfo info, bool _) { 
        completer.complete(info.image));
      })
    ...
    ...

ORIGINAL VERSION:

If you already have an Image widget, you can read the ImageStream out of it by calling resolve on its ImageProvider.

import 'dart:ui' as ui;
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(new MaterialApp(
    home: new MyHomePage(),
  ));
}

class MyHomePage extends StatelessWidget {

  Widget build(BuildContext context) {
    Image image = new Image.network('https://i.stack.imgur.com/lkd0a.png');
    Completer<ui.Image> completer = new Completer<ui.Image>();
    image.image
      .resolve(new ImageConfiguration())
      .addListener((ImageInfo info, bool _) => completer.complete(info.image));
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Image Dimensions Example"),
      ),
      body: new ListView(
        children: [
          new FutureBuilder<ui.Image>(
            future: completer.future,
            builder: (BuildContext context, AsyncSnapshot<ui.Image> snapshot) {
              if (snapshot.hasData) {
                return new Text(
                  '${snapshot.data.width}x${snapshot.data.height}',
                  style: Theme.of(context).textTheme.display3,
                );
              } else {
                return new Text('Loading...');
              }
            },
          ),
          image,
        ],
      ),
    );
  }
}

image_size_getter, Get image width and height, the library does not completely decode the image file, just read the metadata to get the image width and height. This Flutter tutorial gives examples of how to display an image stored in asset folder and adjust the image width, height, color, etc. The images that will be displayed must be stored in particular folders.

The other answers seem overly complicated if you just want the width and height of an image in an async function. You can get the image resolution using flutter lib directly like this:

import 'dart:io';

File image = new File('image.png'); // Or any other way to get a File instance.
var decodedImage = await decodeImageFromList(image.readAsBytesSync());
print(decodedImage.width);
print(decodedImage.height);

width property - Image class - widgets library - Dart , If null, the image will pick a size that best preserves its intrinsic aspect ratio. It is strongly recommended that either both the width and the height be specified,� The default value of height and width is Zero in SizedBox. We would also used Container widget in this tutorial. Both SizedBox and Container widgets works same in flutter. So in this tutorial we would Create Fixed Width Height Size View using SizedBox and Container Widget in flutter android iOS app example.

You can resolve the ImageProvider to get an ImageStream, then use addListener to be notified when the image is ready.

import 'dart:ui' as ui;
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(new MaterialApp(
    home: new MyHomePage(),
  ));
}

class MyHomePage extends StatelessWidget {

  Future<ui.Image> _getImage() {
    Completer<ui.Image> completer = new Completer<ui.Image>();
    new NetworkImage('https://i.stack.imgur.com/lkd0a.png')
      .resolve(new ImageConfiguration())
      .addListener((ImageInfo info, bool _) => completer.complete(info.image));
    return completer.future;
  }

  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Image Dimensions Example"),
      ),
      body: new Center(
        child: new FutureBuilder<ui.Image>(
          future: _getImage(),
          builder: (BuildContext context, AsyncSnapshot<ui.Image> snapshot) {
            if (snapshot.hasData) {
              ui.Image image = snapshot.data;
              return new Text(
                '${image.width}x${image.height}',
                style: Theme.of(context).textTheme.display4);
            } else {
              return new Text('Loading...');
            }
          },
        ),
      ),
    );
  }
}

ResizeImage class - painting library - Dart API, Whether the width and height parameters should be clamped to the intrinsic width and height of the image. [] final. hashCode → int: The hash code for this object. flutter: SIZE of Red: Size(375.0, 152.9) flutter: POSITION of Red: Offset(0.0, 76.0) Finally!!! You can also review this package created by my friend Simon Lightfoot here: https://pub.dartlang.org

Create a method, like:

Future<Size> _calculateImageDimension() {
  Completer<Size> completer = Completer();
  Image image = Image.network("https://i.stack.imgur.com/lkd0a.png");
  image.image.resolve(ImageConfiguration()).addListener(
    ImageStreamListener(
      (ImageInfo image, bool synchronousCall) {
        var myImage = image.image;
        Size size = Size(myImage.width.toDouble(), myImage.height.toDouble());
        completer.complete(size);
      },
    ),
  );
  return completer.future;
}

And use it like:

_calculateImageDimension().then((size) => print("size = ${size}")); // 487.0,696.0

Image class - image library - Dart API, Image(int width, int height, {Channels channels: Channels.rgba, ExifData exif, allows image encoders that support both rgb and rgba formats, to know which� I am new to Flutter and I like it but I am not comfortable building layouts. I am working on an app that contains a ListView of Cards. Each card is inside a Container and contains an image (with fixed height and width) and a text. I am not able to place the image correctly inside the Card. I want the image to cover the width of box. Thanks.

With new version of flutter old solution not working example:

  image.image
  .resolve(new ImageConfiguration())
  .addListener((ImageInfo info, bool _) => completer.complete(info.image));

Below the Working version:

_image.image
    .resolve(new ImageConfiguration())
    .addListener(new ImageStreamListener((ImageInfo image, bool _) {
  completer.complete(image.image);
}));

Flutter - Display and Adjust Images from Assets, How to display image from assets in Flutter and adjust the image size, color, etc. image stored in asset folder and adjust the image width, height, color, etc. by default, in Flutter you can define where the images are stored. CSS has the concept of percentages, so I could just set height and width to 100%. But it doesn't seem like Flutter has that concept, and it's bad to just hard code

Images, This function accepts an optional width and height; if these do not match the image's Each ImageStream is associated with a key that can be used to determine� Flutter has a inbuilt package named as MediaQuery.MediaQuery class is used to get current media screen dimensions known as device screen size. There is a widget named as FractionallySizedBox in flutter which directly supports width height in percentage format but there is a loop in FractionallySizedBox widget.

Get image size in flutter, If the maximum width is infinite, the initial width is determined by applying the aspect ratio to the maximum height. Oct 14, 2019 � Flutter offers a lot of features for� If non-null, require the image to have this width. If null, the image will pick a size that best preserves its intrinsic aspect ratio. It is strongly recommended that either both the width and the height be specified, or that the widget be placed in a context that sets tight layout constraints, so that the image does not change size as it loads.

How to display images from internet in Flutter?, Step by step guide on how to display images from internet in Flutter. The url and width of image are used in the example as arguments. height: 500.0,.

Comments
  • @quertzguy stackoverflow.com/a/55428773/12565404 you solution works perfect :) thanks
  • we need to update this answer. The addListener needs an ImageStreamListener. Even with that I get an error at this line completer.complete(info.image) saying The argument type 'Image' can't be assigned to the parameter type 'FutureOr<Image>
  • If offline, how to calculate the size?
  • Looks like it's in the UI lib - import 'dart:ui';
  • @ajplumlee33 I didn't have to import it in my code. But maybe it's imported from another import? Are imports transcient in dart?
  • This returns a lot more height than the actual height of image. When I use this value to set height I get a lot of extra space at top and bottom.
  • @sakina: open the image in an image editor to check the height and compare it with what this function returns. It should be the same. The issue might be in the layout you are using.
  • @qwertzguy I think its related to scaling of the image, i.e conversion from actual resolution to logical pixels. Because if I give the height returned by the above function to the image there is a lot of empty space, but if no height is given it renders properly. Any idea how to determine this scale?
  • Thanks! So basically I can't use image widget if I want to know wishes and height?
  • I didn't say that! I'll add another answer to show another way.
  • NOTE: when you use this code, it is not possible to save the image -- image.writeAsBytes(result) fail quietly
  • If offline, how to calculate?
  • Use Image.file(your_file) if you have a File.
  • you are my lifesaver, wasted a lot of time before get your solution
  • I can confirm this is the new way of adding a listener, but I get an error on completer.complete(image.image); : The argument of type Image can't be assigned to the type parameter FutureOr<Image>. How can this solved?