如果没有引入flutter_cache_manager库需要引入
例如flutter_cache_manager: 3.3.0
import 'package:image/image.dart' as image;
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
_compressImage(String mirrorImage){
Uint8List imageBytes;
if(mirrorImage.startsWith('http')){
final File file = await DefaultCacheManager().getSingleFile(mirrorImage);
final image.Image thumbnail = image.decodeImage(file.readAsBytesSync());
imageBytes = thumbnail.getBytes();
}else{
imageBytes = await File(mirrorImage).readAsBytes();
}
print("图片初始大小:${
imageBytes .length/ 1024 /1024}MB");
if (imageBytes.length > 1024 * 1024 * 0.5) {
int _quality = 90;
while(imageBytes.length > 1024 * 1024 * 0.5 && _quality>0){
imageBytes = Uint8List.fromList(image.encodeJpg(thumbnail,quality: _quality));
_quality -= 2;
}
print("图片压缩后大小:${
thumbData.length} ${
thumbData.length/ 1024 / 1024}MB");
}
}