Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

getLessLimitSizeImage - 副本.js 1.1KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. // 压缩上传图片
  2. export function translate(imgSrc, scale, fileName, callback) {
  3. let img = new Image();
  4. img.src = imgSrc;
  5. img.onload = function() {
  6. let that = this;
  7. let h = that.height * 0.8; // 默认按比例压缩
  8. let w = that.width * 0.8;
  9. let canvas = document.createElement('canvas');
  10. let ctx = canvas.getContext('2d');
  11. let width = document.createAttribute("width");
  12. width.nodeValue = w;
  13. let height = document.createAttribute("height");
  14. height.nodeValue = h;
  15. canvas.setAttributeNode(width);
  16. canvas.setAttributeNode(height);
  17. ctx.drawImage(that, 0, 0, w, h);
  18. // 设置边框样式
  19. ctx.strokeStyle = '#fff';
  20. ctx.lineWidth = 5;
  21. ctx.strokeRect(0, 0, w, h);
  22. let dataurl = canvas.toDataURL('image/jpeg', scale); //压缩比例
  23. let arr = dataurl.split(','),
  24. mime = arr[0].match(/:(.*?);/)[1],
  25. bstr = atob(arr[1]),
  26. n = bstr.length,
  27. u8arr = new Uint8Array(n);
  28. while (n--) {
  29. u8arr[n] = bstr.charCodeAt(n);
  30. }
  31. let file = new File([u8arr], fileName, {
  32. type: mime
  33. });
  34. // file.lastModifiedDate = new Date();
  35. canvas = null;
  36. callback && callback(dataurl, file);
  37. }
  38. }