初始化

This commit is contained in:
谢宇宁
2026-09-15 15:44:13 +07:00
commit a23ba685e9
1065 changed files with 101122 additions and 0 deletions
@@ -0,0 +1,83 @@
library flutter_native_image;
import 'dart:io';
import 'dart:math' as math;
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:image/image.dart' as img;
import 'package:path/path.dart' as p;
class ImageProperties {
const ImageProperties({
required this.width,
required this.height,
});
final int width;
final int height;
}
class FlutterNativeImage {
static Future<ImageProperties> getImageProperties(String path) async {
final bytes = await File(path).readAsBytes();
final decodedImage = img.decodeImage(bytes);
if (decodedImage == null) {
throw StateError('Unable to decode image at $path');
}
return ImageProperties(
width: decodedImage.width,
height: decodedImage.height,
);
}
static Future<File> compressImage(
String path, {
int quality = 95,
int percentage = 100,
int? targetWidth,
int? targetHeight,
}) async {
final sourceFile = File(path);
final properties = await getImageProperties(path);
final extension = p.extension(path).toLowerCase();
final format = _formatForExtension(extension);
final resizedWidth = targetWidth ??
math.max(1, (properties.width * percentage / 100).round());
final resizedHeight = targetHeight ??
math.max(1, (properties.height * percentage / 100).round());
final targetPath = p.join(
sourceFile.parent.path,
'${p.basenameWithoutExtension(path)}_compressed_${DateTime.now().microsecondsSinceEpoch}${extension.isEmpty ? '.jpg' : extension}',
);
final compressedFile = await FlutterImageCompress.compressAndGetFile(
path,
targetPath,
minWidth: resizedWidth,
minHeight: resizedHeight,
quality: quality,
format: format,
keepExif: true,
);
if (compressedFile == null) {
throw StateError('Unable to compress image at $path');
}
return File(compressedFile.path);
}
static CompressFormat _formatForExtension(String extension) {
switch (extension) {
case '.png':
return CompressFormat.png;
case '.heic':
return CompressFormat.heic;
case '.webp':
return CompressFormat.webp;
default:
return CompressFormat.jpeg;
}
}
}