image_info_handler.dart
2.74 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import 'dart:io';
import 'dart:ui' as ui;
import 'package:appframe/services/dispatcher.dart';
import 'package:appframe/utils/file_type_util.dart';
import 'package:dio/dio.dart';
import 'package:exif/exif.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
class ImageInfoHandler extends MessageHandler {
@override
Future<dynamic> handleMessage(params) async {
if (params is! Map<String, dynamic>) {
throw Exception('参数错误');
}
final url = params['url'] as String;
String filePath;
if (url.startsWith('http')) {
// 获取后缀名
String ext = path.extension(url);
// 获取应用文档目录路径
final Directory tempDir = await getApplicationDocumentsDirectory();
final targetPath = path.join(tempDir.path, '${DateTime.now().millisecondsSinceEpoch}$ext');
final resp = await Dio().download(url, targetPath);
if (resp.statusCode != 200) {
throw Exception('文件下载失败');
}
filePath = targetPath;
} else {
filePath = url;
}
// 读取图片信息
final file = File(filePath);
if (!file.existsSync()) {
throw Exception('图片文件不存在');
}
final bytes = await file.readAsBytes();
// 获取基本图片信息(宽高)
final codec = await ui.instantiateImageCodec(bytes);
final frameInfo = await codec.getNextFrame();
final image = frameInfo.image;
int width = image.width;
int height = image.height;
// 读取 EXIF 信息
int? orientation;
final exifData = await readExifFromBytes(bytes);
if (exifData.isNotEmpty && exifData.containsKey('Image Orientation')) {
final orientationTag = exifData['Image Orientation'];
if (orientationTag != null) {
orientation = orientationTag.values.firstAsInt();
}
}
String orientationStr;
switch (orientation) {
case 1:
orientationStr = 'up';
break;
case 2:
orientationStr = 'up-mirrored';
break;
case 3:
orientationStr = 'down';
break;
case 4:
orientationStr = 'down-mirrored';
break;
case 5:
orientationStr = 'left-mirrored';
break;
case 6:
orientationStr = 'left';
break;
case 8:
orientationStr = 'right';
break;
default:
orientationStr = 'up';
}
// 获取MIME类型并转换为文件扩展名
final mimeType = await FileTypeUtil.getMimeType(file);
final fileExtension = FileTypeUtil.getExtensionFromMime(mimeType);
return {
'tempFilePath': '/temp$filePath',
'width': width,
'height': height,
'orientation': orientationStr,
'type': fileExtension,
};
}
}