如何在flutter中将小部件屏幕截图存储为jpg文件?

时间:2020-06-12 04:28:01

标签: flutter dart

我已经拍摄了一个小部件屏幕截图,我想将其另存为.jpg文件。我能够将其另存为.png文件,但是我不知道如何将其另存为.jpg文件。这是我的代码:

RenderRepaintBoundary boundary = _repainkey.currentContext.findRenderObject();
ui.Image image = await boundary.toImage();
ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
Uint8List pngBytes = byteData.buffer.asUint8List();

final directory = (await getExternalStorageDirectory());
print(directory.path);
File imgFile = new File('${directory.path}/flutter2.png');
await imgFile.writeAsBytes(pngBytes);

1 个答案:

答案 0 :(得分:0)

您必须进行文件类型转换。您可以使用image package来帮助您完成此操作。 This answer与您要查找的内容非常相似,只是将转换与您想要的相反。

链接答案中的示例:

import 'dart:io';
import 'package:image/image.dart';
void main() {
  // Read a jpeg image from file.
  Image image = decodeImage(new File('test.jpg').readAsBytesSync());

  // Resize the image to a 120x? thumbnail (maintaining the aspect ratio).
  Image thumbnail = copyResize(image, 120);

  // Save the thumbnail as a PNG.
  new File('out/thumbnail-test.png')
    ..writeAsBytesSync(encodePng(thumbnail));
}

import 'dart:io';
import 'package:image/image.dart';
void main() {
  // Read a jpeg image from file.
  Image image = decodeImage(new File('test.png').readAsBytesSync());

  // Resize the image to a 120x? thumbnail (maintaining the aspect ratio).
  Image thumbnail = copyResize(image, 120);

  // Save the thumbnail as a PNG.
  new File('out/thumbnail-test.jpg')
    ..writeAsBytesSync(encodeJpg(thumbnail));
}