【Flutter】支持多平台 多端保存图片到本地相册 (兼容 Web端 移动端 android 保存到本地)

免责声明: 我只测试了Web端 和 Android端 可行哈

import 'dart:io';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:universal_html/html.dart' as html;
import 'package:oktoast/oktoast.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';




//申请存 本地存储 和 相册 权限
Future<bool> getPhotoPermission() async {
  if (Platform.isIOS) {
    var storageStatus = await Permission.storage.status;
    var photosStatus = await Permission.photos.status;
    if (storageStatus.isDenied || photosStatus.isDenied) {
      Map<Permission, PermissionStatus> statuses = await [
        Permission.storage,
        Permission.photos,
      ].request();
    }
    return storageStatus.isGranted && photosStatus.isGranted;
  } else {
    var storageStatus = await Permission.storage.status;
    var photosStatus = await Permission.photos.status;
    if (storageStatus.isDenied || photosStatus.isDenied) {
      Map<Permission, PermissionStatus> statuses = await [
        Permission.storage,
        Permission.photos,
      ].request();
    }
    return storageStatus.isGranted && photosStatus.isGranted;
  }
}

// 根据网络路径保存图片到相册
Future<void> saveImage(String imageUrl) async {
  final response = await http.get(Uri.parse(imageUrl));
  final bytes = response.bodyBytes;


  if (kIsWeb) {
    final imageData = Uint8List.fromList(bytes);
    final blob = html.Blob([imageData], 'image/jpeg');
    final url = html.Url.createObjectUrlFromBlob(blob);
    final anchor = html.AnchorElement(href: url);
    String timestamp = DateTime.now().millisecondsSinceEpoch.toString();
    anchor.download = 'image_$timestamp.jpg';
    anchor.click();
    html.Url.revokeObjectUrl(url);
  } else {
    if (Platform.isAndroid || Platform.isIOS) {
      bool permission = await getPhotoPermission();
      if (permission) {
        if (Platform.isIOS) {
          // 自动以时间戳命名
          final result = await ImageGallerySaver.saveImage(bytes);
          if (result != null) {
            showToast("保存成功");
          } else {
            print('error');
          }
        } else {
          //安卓
          // 自动以时间戳命名
          final result = await ImageGallerySaver.saveImage(bytes);
          if (result != null) {
            showToast("保存成功");
          } else {
            print('error');
          }
        }
      } else {
        //重新请求--第一次请求权限时,保存方法不会走,需要重新调一次
        saveImage(imageUrl);
      }
    } else {
      throw PlatformException(
        code: 'PLATFORM_NOT_SUPPORTED',
        message: 'Saving images is not supported on this platform.',
      );
    }
  }
}

你可能感兴趣的:(flutter,前端,android)