encodeToBytes static method

Future<ByteData?> encodeToBytes({
  1. required Image image,
  2. MPFlutterImageByteFormat format = MPFlutterImageByteFormat.png,
  3. double compressQuality = 0.92,
})

不建议使用该方法,该方法使用 base64.decode 会导致严重卡顿。 建议使用 encodeToFilePath 或 encodeToBase64

Implementation

static Future<ByteData?> encodeToBytes({
  required ui.Image image,
  MPFlutterImageByteFormat format = MPFlutterImageByteFormat.png,
  double compressQuality = 0.92,
}) async {
  final rawRgba = await image.toByteData(format: ui.ImageByteFormat.rawRgba);
  if (rawRgba == null) return null;
  final completer = Completer<ByteData?>();
  (mpjs.context["encodeImage"] as mpjs.JSFunction).call([
    rawRgba.buffer.asUint8List(),
    image.width,
    image.height,
    "image/${format.name}",
    compressQuality,
    (String result) {
      try {
        final data = base64.decode(result.split("base64,")[1]);
        completer.complete(ByteData.view(data.buffer));
      } catch (e) {
        completer.complete(null);
      }
    }
  ]);
  return completer.future;
}