如何在Flutter中使用multi_image_picker调整图像大小? [英] How to resize image using multi_image_picker in Flutter?

查看:675
本文介绍了如何在Flutter中使用multi_image_picker调整图像大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 multi_image_picker 包来选择图像并上传到服务器,但是在上传之前调整图像大小。我正在尝试使用 dart.ui 来实现它,但是有一个问题:

I'm using multi_image_picker package to pick images and upload to server, but before uploading I want to resize images. I'm trying to accomplish it using dart.ui but having a problem:

//assets is List<Asset> from MultiImagePicker.pickImages
 assets.forEach((asset) {
      Future<ByteData> byteData = asset.getByteData();
      byteData.then((d) async {
        List<int> imageData = d.buffer.asUint8List();
        String b64 =base64Encode(imageData);
        print(b64); // prints [/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE...
        //if i send b64 to server then decode it and save as img it's working well

  //Resize
    ui.instantiateImageCodec(imageData,targetHeight: 800, targetWidth: 600)
        .then((codec) {
      codec.getNextFrame().then((frameInfo) async {
        ui.Image i = frameInfo.image;
        ByteData bytes = await i.toByteData();
        List<int> resizedImageData = bytes.buffer.asUint8List();
        String rb64 = base64Encode(resizedImageData);
        print(rb64); // prints too many backslashes:[k5KO/5qWk/+ZlZL/mpaT/5uXlP+alpP/mJSR/5iUkf+YlJH/mZSR/5uWk/+blpP/n5qX/6GcmP+gm5f/oZyY/6GcmP+fmpb/nZi..
        //If i send rb64 to server then server cannot decode and save it.
      });
    });
  });
});


推荐答案

这是我通常用来调整大小的函数:

This is the function I normally use to resize:

import 'dart:ui' as skia;

Future<skia.Image> resizeImage(String path, {int width, int height}) async {
  Uint8List data = await File(path).readAsBytes();
  final codec = await skia.instantiateImageCodec(data, targetWidth: width, targetHeight: height);
  final frame = await codec.getNextFrame();
  return frame.image;
}

正如我在评论中提到的那样,当前在Flutter Web中不起作用,但是

As I mentioned in the comment, this is currently not working in Flutter Web but it's due to a bug that will be fixed soon, hopefully.

这篇关于如何在Flutter中使用multi_image_picker调整图像大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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