有替代image_picker_saver依赖项的方法吗

时间:2019-05-20 12:04:47

标签: image flutter download

我正在编写代码以在设备中下载图像,但是androidx与image_picker_saver依赖项不兼容。那么有人可以建议替代方法吗?

The complete code-
     _saveImage(imageNames) async {
await PermissionHandler()
    .checkPermissionStatus(PermissionGroup.storage)
    .then((status) async {
  if (status == PermissionStatus.denied ||
      status == PermissionStatus.disabled ||
      status == PermissionStatus.unknown) {
    await PermissionHandler().requestPermissions(
        [PermissionGroup.storage]).then((status1) async {
      if (status1.containsValue(PermissionStatus.granted)) {
        await get(imageNames).then((res) async {
          await ImagePickerSaver.saveFile(fileData: res.bodyBytes)
              .then((str) {
            File.fromUri(Uri.file(str));
            Fluttertoast.showToast(
                msg: "Saved to gallery!",
                toastLength: Toast.LENGTH_LONG,
                gravity: ToastGravity.BOTTOM,
                timeInSecForIos: 1,
                backgroundColor: Colors.green,
                textColor: Colors.white,
                fontSize: 15.0);
          });
        });
      }
    });
  } else if (status == PermissionStatus.granted) {
    await get(imageNames).then((res) async {
      await ImagePickerSaver.saveFile(fileData: res.bodyBytes).then((str) {
        File.fromUri(Uri.file(str));
        Fluttertoast.showToast(
            msg: "Saved to gallery!",
            toastLength: Toast.LENGTH_LONG,
            gravity: ToastGravity.CENTER,
            timeInSecForIos: 1,
            backgroundColor: Colors.green,
            textColor: Colors.white,
            fontSize: 15.0);
      });
    });
  }
});

}

1 个答案:

答案 0 :(得分:0)

您需要一个用于解码/编码算法的软件包。我建议这个规范化的包: https://pub.dev/packages/image

我们将使用它。

import 'dart:io' as io;
import 'package:http/http.dart' as http;
import 'package:image/image.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';

我们需要bodyBytes来从网络映像文件写入文件:

Future<dynamic> downloadImage() async =>
    await http.get(url).then((response) => response.bodyBytes);

获取应用程序工作目录:

Future<String> createDir() async =>
    await getApplicationDocumentsDirectory().then((dir) => dir.path);

首先,我们将创建由图像包提供的[Image]类型变量,然后将其再次转换为图像包提供的解码和编码文件:

Future<io.File> writeFile(String path, var bodyBytes, String fileName) async {
  Image image = decodeImage(bodyBytes);
  io.File file = io.File(join(path, fileName));
  file.writeAsBytesSync(encodePng(image));
  return file;
}

因此,您创建了文件,需要加载它们,这是您需要的方法(您可以通过[Image.file]小部件使用还原的图像):

Future<List<io.File>> loadFiles() async {
  List<io.File> images = <io.File>[];
  final io.Directory dir = await getApplicationDocumentsDirectory();
  print('path: ${dir.path}');
  for (io.FileSystemEntity f in dir.listSync()) {
    if (f is io.File) {
      if (f.path.contains('.jpg')) { //any format you want
        images.add(f);
      }
    }
  }
  return images;
}