天天看点

Flutter 获取图片宽高

实现思路

先读取图片到ui.Image,再调用image.width image.height属性拿到宽高

代码

注:需要先import ‘dart:ui’ as ui;

static Future<ui.Image> loadImage(String url) async {
    AssetBundle _bundle = rootBundle;
    ImageStream stream = new AssetImage(url, bundle: _bundle).resolve(ImageConfiguration.empty);
    Completer<ui.Image> completer = new Completer<ui.Image>();
    ImageStreamListener listener;
    listener = new ImageStreamListener(
            (ImageInfo frame, bool synchronousCall) {
          final ui.Image image = frame.image;
          completer.complete(image);
          stream.removeListener(listener);
        });
    stream.addListener(listener);
    return completer.future;
  }

  static Future<ui.Image> loadImageFromFile(String url) async {
    AssetBundle _bundle = rootBundle;
    ImageStream stream = new FileImage(File.fromUri(Uri.parse(url)),).resolve(ImageConfiguration.empty);
    Completer<ui.Image> completer = new Completer<ui.Image>();
    ImageStreamListener listener;
    listener = new ImageStreamListener(
            (ImageInfo frame, bool synchronousCall) {
          final ui.Image image = frame.image;
          completer.complete(image);
          stream.removeListener(listener);
        });
    stream.addListener(listener);
    return completer.future;
  }