utils.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /**
  2. * 图片压缩方法,压缩base64格式图片
  3. * @param {Object} base64
  4. * @param {Object} w
  5. */
  6. function compressImage(base64, w) {
  7. return new Promise((resolve, reject) => {
  8. var img = new Image();
  9. var quality = 0.6; //压缩系数0-1之间
  10. img.src = base64;
  11. img.setAttribute("crossOrigin", 'Anonymous'); //url为外域时需要
  12. img.onload = function() {
  13. // 等比缩放
  14. let width = img.width;
  15. let height = img.height;
  16. console.log('++++orginal w:' + width + ',h:' + height)
  17. if (width > w) {
  18. const rate = height / width
  19. height = parseInt(w * rate)
  20. width = w
  21. }
  22. var canvas = document.createElement("canvas");
  23. var ctx = canvas.getContext("2d");
  24. canvas.width = width;
  25. canvas.height = height;
  26. quality = 0.8;
  27. console.log('++++compress w:' + width + ',h:' + height)
  28. ctx.clearRect(0, 0, canvas.width, canvas.height);
  29. ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
  30. const base64 = canvas.toDataURL("image/jpeg", quality); //压缩语句
  31. resolve(base64);
  32. }
  33. })
  34. }
  35. module.exports = {
  36. compressImage: compressImage
  37. }