import 'package:crypto/crypto.dart'; import 'package:flutter/cupertino.dart'; import 'dart:convert'; import 'dart:io'; import 'package:flutter_native_image/flutter_native_image.dart'; import 'package:zhiying_comm/util/dialog/loading/loading.dart'; import 'package:zhiying_comm/zhiying_comm.dart'; class EncodeUtil { /* * Md5加密 * */ static String generateMd5(String data) { var content = new Utf8Encoder().convert(data); var digest = md5.convert(content); return digest.toString(); } /* * Base64加密 */ static String encodeBase64(String data) { var content = utf8.encode(data); var digest = base64Encode(content); return digest; } /* * Base64解密 */ static String decodeBase64(String data) { // return String.fromCharCodes(base64Decode(data)); return utf8.decode(base64Decode(data)); } // 图片转成base64 static Future image2Base64(File file) async { // File file = new File(path); List imageBytes = await file.readAsBytes(); return base64Encode(imageBytes); } // 压缩图片至指定大小 static Future compressImage(BuildContext context, {File file, List images, int size}) async { List originBytes; if (images != null) { originBytes = images; Directory dir = await getTemporaryDirectory(); File tempFile = File(dir.path + "/temp.png"); tempFile = await tempFile.writeAsBytes(originBytes); file = tempFile; } else if (file != null) { originBytes = await file.readAsBytes(); } else { return null; } int originSize = (originBytes.length / 1024).ceil(); print('原图大小:' + originSize.toString() + 'kb'); if (originSize <= size) { return file; } int minQuality = 0; int maxQuality = 100; List imageBytes = originBytes; do { int midQuality = ((minQuality + maxQuality) / 2).floor(); File compressedFile = await FlutterNativeImage.compressImage(file.path, quality: midQuality); imageBytes = await compressedFile.readAsBytes(); int compressSize = (imageBytes.length / 1024).ceil(); if (compressSize == size) { break; } else if (compressSize > size) { maxQuality = midQuality; } else { minQuality = midQuality; } } while (maxQuality - minQuality > 1); File compressedFile = await FlutterNativeImage.compressImage(file.path, quality: minQuality); imageBytes = await compressedFile.readAsBytes(); int compressSize = (imageBytes.length / 1024).ceil(); print('quality:' + minQuality.toString() + ' 压缩后大小:' + compressSize.toString() + 'kb'); return compressedFile; } }