saveToGallery static method
将图片保存到系统相册
source 图片来源,支持:
String:本地文件路径或网络 URLUint8List:原始字节数据XFile:来自 image_picker 等平台插件的文件对象
album 相册名称;相册不存在时由系统自动创建。
iOS 会创建以 album 命名的相册,Android 行为取决于系统版本。
返回 ImageResult<String>,data 为相册中保存的文件路径。
Implementation
static Future<ImageResult<String>> saveToGallery(
dynamic source, {
String album = 'App Photos',
}) async {
if (source == null) {
return const ImageResult.failure('source 不能为空');
}
try {
String filePath;
if (source is String) {
if (source.startsWith('http://') || source.startsWith('https://')) {
// 网络 URL:下载到临时文件
final tmpDir = await getTemporaryDirectory();
final urlHash = md5.convert(source.codeUnits).toString();
final tmpPath = '${tmpDir.path}/gal_tmp_$urlHash.jpg';
await Dio().download(source, tmpPath);
filePath = tmpPath;
} else {
filePath = source;
}
} else if (source is Uint8List) {
final tmpDir = await getTemporaryDirectory();
final tmpPath =
'${tmpDir.path}/gal_tmp_${DateTime.now().millisecondsSinceEpoch}.jpg';
await File(tmpPath).writeAsBytes(source);
filePath = tmpPath;
} else if (source is XFile) {
filePath = source.path;
} else {
return const ImageResult.failure('不支持的 source 类型');
}
// 写入相册
await Gal.putImage(filePath, album: album);
return ImageResult.success(filePath);
} catch (e) {
return ImageResult.failure(e.toString());
}
}