51 lines
1.3 KiB
Dart
51 lines
1.3 KiB
Dart
import 'dart:io';
|
|
import 'package:crypto/crypto.dart';
|
|
import 'package:flutter_image_compress/flutter_image_compress.dart';
|
|
|
|
import 'log_utils.dart';
|
|
|
|
String getFileExtension(String fileName) {
|
|
if (fileName.contains('.')) {
|
|
return '.${fileName.split('.').last.toLowerCase()}';
|
|
}
|
|
return '';
|
|
}
|
|
|
|
Future<String> generateMD5HashName(String filePath) async {
|
|
final file = File(filePath);
|
|
final bytes = await file.readAsBytes();
|
|
final hash = md5.convert(bytes);
|
|
return hash.toString();
|
|
}
|
|
|
|
// 图片压缩方法
|
|
Future<File> compressImage(File file) async {
|
|
try {
|
|
// 获取压缩后的文件路径
|
|
final result = await FlutterImageCompress.compressAndGetFile(
|
|
file.absolute.path,
|
|
'${file.parent.path}/compressed_${DateTime.now().millisecondsSinceEpoch}.jpg',
|
|
minWidth: 800,
|
|
minHeight: 600,
|
|
quality: 70,
|
|
format: CompressFormat.jpeg,
|
|
);
|
|
|
|
if (result == null) {
|
|
throw Exception('图片压缩失败');
|
|
}
|
|
|
|
return File(result.path);
|
|
} catch (e) {
|
|
logger.e('图片压缩失败,使用原文件: $e');
|
|
return file;
|
|
}
|
|
}
|
|
|
|
// 检查是否为图片文件
|
|
bool isImageFile(String fileName) {
|
|
final imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'];
|
|
final extension = fileName.toLowerCase().substring(fileName.lastIndexOf('.'));
|
|
return imageExtensions.contains(extension);
|
|
}
|