基础库
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 

80 líneas
2.1 KiB

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