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!
We will use AspectRatio() widget to achieve aspect ratio on the Image widget in Flutter.
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);
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)); }) ... ...
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, ], ), ); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With