compressPhoto.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import methods from "@/common/methodTool";
  2. let num = 1;
  3. let _resolve;
  4. let _reject;
  5. function getBase64Size(base64) {
  6. if (base64) {
  7. base64 = base64.split(",")[1].split("=")[0];
  8. var strLength = base64.length;
  9. var fileLength = strLength - (strLength / 8) * 2;
  10. return Math.floor(fileLength); // 向下取整
  11. } else {
  12. return null;
  13. }
  14. }
  15. //获得图片大小
  16. function imageSizeIsLessLimitSize(imagePath, limitSize) {
  17. return new Promise((resolve, reject) => {
  18. wx.getFileSystemManager().getFileInfo({
  19. filePath: imagePath,
  20. success: (res) => {
  21. resolve(res.size);
  22. },
  23. });
  24. });
  25. }
  26. //主函数,默认限制大小2048kb即2mb,drawWidth是绘画区域的大小
  27. //初始值传入为画布自身的边长(我们这是一个正方形的画布)
  28. function getLessLimitSizeImage(imagePath, quality) {
  29. uni.compressImage({
  30. src: imagePath,
  31. quality: quality * 100,
  32. success: (res) => {
  33. console.log(res.tempFilePath, res, "压缩后");
  34. _resolve(res.tempFilePath);
  35. },
  36. });
  37. }
  38. function compressH5(url, quality) {
  39. let image = new Image();
  40. image.onload = function () {
  41. var canvas = document.createElement("canvas");
  42. canvas.width = image.width;
  43. canvas.height = image.height;
  44. var ctx = canvas.getContext("2d");
  45. ctx.drawImage(image, 0, 0, this.height, this.width); //压缩比例
  46. var base64 = canvas.toDataURL("image/jpeg", quality);
  47. _resolve(base64);
  48. };
  49. image.src = url;
  50. image.setAttribute("crossOrigin", "Anonymous");
  51. image.onerror = () => {
  52. _reject(new Error("zip error"));
  53. };
  54. }
  55. function myCompressImage(url, limitSize = 2048) {
  56. return new Promise(async (resolve, reject) => {
  57. _resolve = resolve;
  58. _reject = resolve;
  59. limitSize = limitSize * 1024;
  60. // 获得size
  61. if (typeof url == "string") {
  62. // base64
  63. if (methods.isBase64(url)) {
  64. url = {
  65. path: url,
  66. size: getBase64Size(url),
  67. };
  68. }
  69. // #ifdef MP-WEIXIN
  70. url = {
  71. path: url,
  72. size: await imageSizeIsLessLimitSize(url),
  73. };
  74. // #endif
  75. }
  76. const size = url.size;
  77. if (size < limitSize) {
  78. return _resolve(url.path);
  79. }
  80. num++;
  81. const quality = limitSize / size;
  82. console.log(size, quality, "压缩前");
  83. // #ifdef MP-WEIXIN
  84. getLessLimitSizeImage(url.path, quality);
  85. // #endif
  86. // #ifdef H5
  87. compressH5(url.path, quality);
  88. // #endif
  89. });
  90. }
  91. export default myCompressImage;