基础库
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 

81 rinda
2.2 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. return utf8.decode(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. }