美文网首页flutter
Flutter图片File转base64并压缩

Flutter图片File转base64并压缩

作者: 倪大头 | 来源:发表于2020-03-19 17:22 被阅读0次

四个头文件:

import 'dart:io';
import 'dart:typed_data';
import 'dart:convert';
import 'package:flutter_image_compress/flutter_image_compress.dart';

最后一个是压缩库,要在pubspec.yaml导入:

flutter_image_compress:

图片转base64并压缩,quality是图片质量,0-100可调整

Future imageToBase64AndCompress(File file) async {
  List<int> imageBytes = await FlutterImageCompress.compressWithFile(file.absolute.path, quality: 20);
  print('压缩图片大小:' + imageBytes.length.toString());
  return base64Encode(imageBytes);
}

图片file转base64,不压缩

Future imageToBase64(File file) async {
  List<int> imageBytes = await file.readAsBytes();
  print('图片大小:' + imageBytes.length.toString());
  return base64Encode(imageBytes);
}

base64转图片

Image base64ToImage(String base64Str, double width, double height) {
  Uint8List bytes = Base64Decoder().convert(base64Str);
  return Image.memory(bytes, fit: BoxFit.cover, width: width, height: height);
}

压缩图片并返回File

Future imageCompressToFile(File file) async {
  print('压缩前图片文件大小:' + file.lengthSync().toString());
  File imageFile = await FlutterImageCompress.compressAndGetFile(
    file.absolute.path,
    Directory.systemTemp.path + '/userava' + myuserId + '.jpg',
    quality: 10,
    minWidth: 200,
    minHeight: 200,
  );
  print('压缩后图片文件大小:' + imageFile.lengthSync().toString());
  return imageFile;
}

Directory.systemTemp.path为tmp路径

相关文章

网友评论

    本文标题:Flutter图片File转base64并压缩

    本文链接:https://www.haomeiwen.com/subject/hcilyhtx.html