基础库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

81 lines
2.2 KiB

  1. import 'package:crypto/crypto.dart';
  2. import 'dart:convert';
  3. import 'dart:io';
  4. import 'dart:typed_data';
  5. import 'package:flutter_native_image/flutter_native_image.dart';
  6. class EncodeUtil {
  7. /*
  8. * Md5加密
  9. * */
  10. static String generateMd5(String data) {
  11. var content = new Utf8Encoder().convert(data);
  12. var digest = md5.convert(content);
  13. return digest.toString();
  14. }
  15. /*
  16. * Base64加密
  17. */
  18. static String encodeBase64(String data) {
  19. var content = utf8.encode(data);
  20. var digest = base64Encode(content);
  21. return digest;
  22. }
  23. /*
  24. * Base64解密
  25. */
  26. static String decodeBase64(String data) {
  27. return String.fromCharCodes(base64Decode(data));
  28. }
  29. // 图片转成base64
  30. static Future<String> image2Base64(File file) async {
  31. // File file = new File(path);
  32. List<int> imageBytes = await file.readAsBytes();
  33. return base64Encode(imageBytes);
  34. }
  35. // 压缩图片至指定大小
  36. static Future<File> compressImage(File file, int size) async {
  37. List<int> originBytes = await file.readAsBytes();
  38. int originSize = (originBytes.length / 1024).ceil();
  39. print('原图大小:' + originSize.toString() + 'kb');
  40. if (originSize <= size) {
  41. return file;
  42. }
  43. int minQuality = 0;
  44. int maxQuality = 100;
  45. List<int> imageBytes = originBytes;
  46. do {
  47. int midQuality = ((minQuality + maxQuality) / 2).floor();
  48. File compressedFile = await FlutterNativeImage.compressImage(file.path,
  49. quality: midQuality);
  50. imageBytes = await compressedFile.readAsBytes();
  51. int compressSize = (imageBytes.length / 1024).ceil();
  52. if (compressSize == size) {
  53. break;
  54. } else if (compressSize > size) {
  55. maxQuality = midQuality;
  56. } else {
  57. minQuality = midQuality;
  58. }
  59. } while (maxQuality - minQuality > 1);
  60. File compressedFile =
  61. await FlutterNativeImage.compressImage(file.path, quality: minQuality);
  62. imageBytes = await compressedFile.readAsBytes();
  63. int compressSize = (imageBytes.length / 1024).ceil();
  64. print('quality:' +
  65. minQuality.toString() +
  66. ' 压缩后大小:' +
  67. compressSize.toString() +
  68. 'kb');
  69. return compressedFile;
  70. }
  71. }