如何在不使用异步的情况下将图像转换为 uint8list? [英] How to convert image to uint8list in flutter without using async?

查看:68
本文介绍了如何在不使用异步的情况下将图像转换为 uint8list?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PdfImage 需要 Uint8List 作为参数,但我有 ImageProvider.那么flutter中如何将image转为uint8list呢?

PdfImage requires Uint8List as param but I have ImageProvider. So how can we convert image to uint8list in flutter?

var imageProvider = AssetImage('assets/test.jpg');

final image = PdfImage(
  pdf.document,
  image:???, /// Uint8List required
  width: img.width,
  height: img.height,
);

使用 FutureBuilder:

推荐答案

使用rootBundle.load()

(await rootBundle.load(/*YOUR IMAGE PATH HERE*/)).buffer.asUint8List()

<小时>

更新

由于 load() 是异步操作,所以需要等到数据完全加载完毕.在此之前尝试用一些加载指示器替换 UI.


UPDATE

As load() is an async operation, you need to wait until the data is fully loaded. Try substituting the UI with some loading indicator until then.

ByteData imageData;

@override
void initState() {
  rootBundle.load('assets/test.jpg')
    .then((data) => setState(() => this.imageData = data));
}

@override
Widget build(BuildContext context) {
  if (imageData == null) {
    return Center(child: CircularProgressIndicator());
  }

  final image = PdfImage(
    pdf.document,
    image: imageData.buffer.asUint8List(),
    width: img.width,
    height: img.height,
  );

  ...
}

这篇关于如何在不使用异步的情况下将图像转换为 uint8list?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆