image.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. export function resize(base64, callback) {
  2. const w = 1440
  3. let newImage = new Image()
  4. let quality = 0.8 //压缩系数
  5. newImage.src = base64
  6. newImage.setAttribute('crossOrigin', 'Anonymous')
  7. let imgWidth, imgHeight
  8. newImage.onload = function () {
  9. imgWidth = this.width
  10. imgHeight = this.height
  11. let canvas = document.createElement('canvas')
  12. let ctx = canvas.getContext('2d')
  13. if (Math.max(imgWidth, imgHeight) > w) {
  14. if (imgWidth > imgHeight) {
  15. canvas.width = w
  16. canvas.height = (w * imgHeight) / imgWidth
  17. } else {
  18. canvas.height = w
  19. canvas.width = (w * imgWidth) / imgHeight
  20. }
  21. } else {
  22. canvas.width = imgWidth
  23. canvas.height = imgHeight
  24. quality = 0.8
  25. }
  26. ctx.clearRect(0, 0, canvas.width, canvas.height)
  27. ctx.drawImage(this, 0, 0, canvas.width, canvas.height)
  28. let base64 = canvas.toDataURL('image/jpeg', quality) // 执行压缩
  29. while (base64.length / 1024 > 500) {
  30. quality -= 0.01
  31. base64 = canvas.toDataURL('image/jpeg', quality)
  32. }
  33. callback(base64)
  34. }
  35. }