petsHero-AI/lib/core/util/image_compress.dart
2026-03-29 23:53:24 +08:00

38 lines
1.1 KiB
Dart
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'dart:io';
import 'package:image/image.dart' as img;
import 'package:path_provider/path_provider.dart';
/// 上传前压缩限制长边、JPEG 质量,减轻内存与带宽;解码失败时返回原文件。
Future<File> compressImageForUpload(
File source, {
int maxSide = 2048,
int jpegQuality = 85,
}) async {
try {
final raw = await source.readAsBytes();
final image = img.decodeImage(raw);
if (image == null) return source;
var work = image;
if (work.width > maxSide || work.height > maxSide) {
if (work.width >= work.height) {
work = img.copyResize(work, width: maxSide, interpolation: img.Interpolation.linear);
} else {
work = img.copyResize(work, height: maxSide, interpolation: img.Interpolation.linear);
}
}
final jpg = img.encodeJpg(work, quality: jpegQuality);
final dir = await getTemporaryDirectory();
final out = File(
'${dir.path}/upload_${DateTime.now().millisecondsSinceEpoch}.jpg',
);
await out.writeAsBytes(jpg, flush: true);
return out;
} catch (_) {
return source;
}
}