Flutter图片宽高获取

  • 本地图片宽高获取
  • 网络图片宽高获取

原理

通过在其ImageProvider上调用resolve来读取ImageStream

1.本地图片宽高获取

以IM发送本地图片为例

sendImage: (String path) async {
  IMImageMsgModel m = IMImageMsgModel(localUrl: path);
  Image image = Image.file(File.fromUri(Uri.parse(path)));
  // 预先获取图片信息
  image.image.resolve(new ImageConfiguration()).addListener(
      new ImageStreamListener((ImageInfo info, bool _) {
    m.width = info.image.width;
    m.height = info.image.height;
    this.sendMsg(m);
  }));
},

2.网络图片宽高获取

自己返回的Message格式:

{timestamp: 1579076501, msgType: Image, message: {imageFormat: 255, imageList: [], level: 1, path: https://ae80-1400284328-1256635546.cos.ap-shanghai.myqcloud.com/e1696b47832dd6e336a6db38b51cd3fd/23a2ad6539b63787dee8909f9bdb60b9.jpg, taskId: 0, type: Image}, msgId: 862520433, seq: 13163, rand: 862520433, isSelf: true, uniqueId: 6782081930539631729, isRead: true, status: 2, timMessageLocator: {rand: 862520433, seq: 13163, timestamp: 1579076501, sid: null, isSelf: true}, sender: e1696b47832dd6e336a6db38b51cd3fd, peer: 5d2806e96205f82dcf692370de0c7e07, customData: null, customInt: 0, customStr: , type: Image}

对方返回的Message格式:

{timestamp: 1579077317, msgType: Image, message: {imageFormat: 1, imageList: [{height: 2160, size: 1185181, type: Original, url: https://ae80-1400284328-1256635546.cos.ap-shanghai.myqcloud.com/5d2806e96205f82dcf692370de0c7e07/0f7b0c259f53770c6eab0cbba550e605.jpg, uuid: 1400284328_5d2806e96205f82dcf692370de0c7e07_0f7b0c259f53770c6eab0cbba550e605.jpg, width: 1080}, {height: 396, size: 0, type: Thumb, url: https://ae80-1400284328-1256635546.picsh.myqcloud.com/5d2806e96205f82dcf692370de0c7e07/0f7b0c259f53770c6eab0cbba550e605.jpg?imageView2/3/w/198/h/198, uuid: 1400284328_5d2806e96205f82dcf692370de0c7e07_0f7b0c259f53770c6eab0cbba550e605.jpg, width: 198}, {height: 1440, size: 0, type: Large, url: https://ae80-1400284328-1256635546.picsh.myqcloud.com/5d2806e96205f82dcf692370de0c7e07/0f7b0c259f53770c6eab0cbba550e605.jpg?imageView2/3/w/720/h/720, uuid: 1400284328_5d2806e96205f82dcf692370de0c7e07_0f7b0c259f53770c6eab0cbba550e605.jpg, width: 720}], level: 1, path: , taskId: 0, type: Image}

当IM回调图片不带宽高时,通过以下方法获取网络图片宽高

IMImageMsgModel model;
Image image = Image.network(this.detail.message['path'] ?? '');
image.image
    .resolve(new ImageConfiguration())
    .addListener(new ImageStreamListener(
      (ImageInfo info, bool _) {
    model = IMImageMsgModel(
      url: this.detail.message['path'],
      width: info.image.width,
      height: info.image.height,
    );
    print('model.width======${model.width}');
  },
));

效果如下

图片宽高为:66-800

效果如下

你可能感兴趣的:(Flutter图片宽高获取)