temirbek
temirbek

Reputation: 1452

How to resize image using multi_image_picker in Flutter?

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.
      });
    });
  });
});

Upvotes: 1

Views: 1645

Answers (1)

G&#225;bor
G&#225;bor

Reputation: 10274

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;
}

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.

Upvotes: 2

Related Questions