save_to_album_handler.dart
2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import 'dart:convert';
import 'dart:io';
import 'package:appframe/services/dispatcher.dart';
import 'package:gallery_saver_plus/gallery_saver.dart';
import 'package:path_provider/path_provider.dart';
class SaveToAlbumHandler extends MessageHandler {
@override
Future<dynamic> handleMessage(dynamic params) async {
if (params is! Map<String, dynamic>) {
throw Exception('参数错误');
}
var filePath = params['filePath'] as String?;
if (filePath == null || filePath.isEmpty) {
return false;
}
String actualFilePath;
if (_isBase64(filePath)) {
actualFilePath = await _saveBase64ToFile(filePath);
} else {
actualFilePath = filePath;
}
bool isVideo = _isVideoFile(actualFilePath);
try {
if (isVideo) {
final bool? success = await GallerySaver.saveVideo(actualFilePath);
return success ?? false;
} else {
final bool? success = await GallerySaver.saveImage(actualFilePath);
return success ?? false;
}
} catch (e) {
print(e);
return false;
}
}
bool _isBase64(String str) {
if (str.startsWith('data:image/')) {
return true;
}
try {
base64Decode(str);
return true;
} catch (e) {
return false;
}
}
Future<String> _saveBase64ToFile(String base64Str) async {
String base64Data = base64Str;
String fileExtension = 'png';
if (base64Str.startsWith('data:image/')) {
final regExp = RegExp(r'data:image/(\w+);base64,(.+)');
final match = regExp.firstMatch(base64Str);
if (match != null) {
fileExtension = match.group(1) ?? 'png';
base64Data = match.group(2) ?? '';
}
}
final bytes = base64Decode(base64Data);
final tempDir = await getTemporaryDirectory();
final filePath = '${tempDir.path}/${DateTime.now().millisecondsSinceEpoch}.$fileExtension';
final file = File(filePath);
await file.writeAsBytes(bytes);
return filePath;
}
bool _isVideoFile(String filePath) {
return filePath.endsWith('.mp4') ||
filePath.endsWith('.avi') ||
filePath.endsWith('.mov') ||
filePath.endsWith('.mkv') ||
filePath.endsWith('.wmv') ||
filePath.endsWith('.flv') ||
filePath.endsWith('.webm') ||
filePath.endsWith('.m4v') ||
filePath.endsWith('.3gp');
}
}